VBA XML возврат - PullRequest
       4

VBA XML возврат

0 голосов
/ 20 апреля 2020

Как заставить VBA вернуть узел XML, который выглядит следующим образом <MondayToFriday />?

Я пробовал модифицированную версию этого, однако я хочу, чтобы пустой тег не являлся атрибутом

Public Function XMLDupCheck()
    Dim xmlDoc      As MSXML2.DOMDocument60
    Dim xmlNodeList As MSXML2.IXMLDOMNodeList
    Dim xmlNode     As MSXML2.IXMLDOMNode
    Dim myNode      As MSXML2.IXMLDOMNode

    ' Create an Instance of the DOMDocument
    Set xmlDoc = New MSXML2.DOMDocument60
    xmlDoc.async = False

    Dim strPathToXMLFile As String
    ' Load XML information from a file. In this case, Cell C3 of Sheet "XML & DB2 Data" should contain the path of the XML
    'strPathToXMLFile = Sheets("Credentials").Range("C3").Value
    strPathToXMLFile = (Sheet1.[addr] & "308_AKT_PK_306_20200418.xml")
    xmlDoc.validateOnParse = True

    If Not xmlDoc.Load(strPathToXMLFile) Then
        MsgBox "Problem"
        Exit Function
    End If

    ' Find out the number of child nodes in the file
    Set xmlNodeList = xmlDoc.getElementsByTagName("*")



    ' Open a new workbook and paste the data

    Worksheets("Map").Select

    Range("A:A").Clear
    Range("B:B").Clear
    ActiveSheet.Cells(1, 1).Select
    r = 2
    c = 1

    Range("A1:B1").Formula = Array("Service Code", "TicketMachineCode")
    ActiveSheet.Cells(2, 1).Select
    For Each xmlNode In xmlNodeList
        For Each myNode In xmlNode.ChildNodes
            If myNode.NodeType = NODE_TEXT Then
                If myNode.ParentNode.ParentNode.BaseName & ":" & xmlNode.nodeName = "TicketMachine:TicketMachineServiceCode" Then
                    Cells(r, c).Value = xmlNode.Text
                    r = r + 1
                End If

            End If

        Next myNode
    Next xmlNode

    r = 2
    c = 2

    ActiveSheet.Cells(2, 2).Select
    For Each xmlNode In xmlNodeList
        For Each myNode In xmlNode.ChildNodes
            If myNode.NodeType = NODE_TEXT Then
                If myNode.ParentNode.ParentNode.BaseName & ":" & xmlNode.nodeName = "TicketMachine:JourneyCode" Then
                    Cells(r, c).Value = xmlNode.Text
                    r = r + 1
                End If

            End If

        Next myNode
    Next xmlNode

    r = 2
    c = 3

    ActiveSheet.Cells(2, 2).Select


End Function
<?xml version="1.0" encoding="UTF-8"?>
<TransXChange xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xmlns="http://www.transxchange.org.uk/"
              xsi:schemaLocation="http://www.transxchange.org.uk/ http://www.transxchange.org.uk/schema/2.1/TransXChange_registration.xsd"
              CreationDateTime="2020-04-09T14:05:22"
              ModificationDateTime="2020-04-09T14:05:22"
              RegistrationDocument="true"
              Modification="new"
              RevisionNumber="0"
              FileName="97_AKE_PF_97_20200413.xml"
              SchemaVersion="2.1">
   <VehicleJourney>
      <PrivateCode>5158618</PrivateCode>
      <Operational>
         <Block>
            <Description>7064</Description>
            <BlockNumber>7064</BlockNumber>
         </Block>
         <TicketMachine>
            <TicketMachineServiceCode>97</TicketMachineServiceCode>
            <JourneyCode>6203</JourneyCode>
         </TicketMachine>
      </Operational>
      <OperatingProfile>
         <RegularDayType>
            <DaysOfWeek>
               <MondayToFriday/>
            </DaysOfWeek>
         </RegularDayType>
         <BankHolidayOperation>
            <DaysOfNonOperation>
               <AllBankHolidays/>
            </DaysOfNonOperation>
         </BankHolidayOperation>
      </OperatingProfile>
      <LayoverPoint>
         <Duration>PT1M0S</Duration>
         <Name>Stotfold, The Green (Southbound)</Name>
         <Location>
            <Longitude>-0.225788</Longitude>
            <Latitude>52.020374</Latitude>
         </Location>
      </LayoverPoint>
      <GarageRef>BR</GarageRef>
      <VehicleJourneyCode>5158618</VehicleJourneyCode>
      <ServiceRef>97</ServiceRef>
      <LineRef>2</LineRef>
      <JourneyPatternRef>1</JourneyPatternRef>
      <DepartureTime>07:20:00</DepartureTime>
      <VehicleJourneyTimingLink id="60">
         <JourneyPatternTimingLinkRef>4</JourneyPatternTimingLinkRef>
         <RunTime>PT1M19S</RunTime>
      </VehicleJourneyTimingLink>
      <VehicleJourneyTimingLink id="61">
         <JourneyPatternTimingLinkRef>5</JourneyPatternTimingLinkRef>
         <RunTime>PT1M41S</RunTime>
      </VehicleJourneyTimingLink>
      <VehicleJourneyTimingLink id="62">
         <JourneyPatternTimingLinkRef>6</JourneyPatternTimingLinkRef>
         <RunTime>PT1M1S</RunTime>
      </VehicleJourneyTimingLink>
      <VehicleJourneyTimingLink id="63">
         <JourneyPatternTimingLinkRef>7</JourneyPatternTimingLinkRef>
         <RunTime>PT0M45S</RunTime>
      </VehicleJourneyTimingLink>
      <VehicleJourneyTimingLink id="64">
         <JourneyPatternTimingLinkRef>8</JourneyPatternTimingLinkRef>
         <RunTime>PT0M48S</RunTime>
      </VehicleJourneyTimingLink>
      <VehicleJourneyTimingLink id="65">
         <JourneyPatternTimingLinkRef>9</JourneyPatternTimingLinkRef>
         <RunTime>PT1M18S</RunTime>
      </VehicleJourneyTimingLink>
      <VehicleJourneyTimingLink id="66">
         <JourneyPatternTimingLinkRef>10</JourneyPatternTimingLinkRef>
         <RunTime>PT1M8S</RunTime>
      </VehicleJourneyTimingLink>
      <VehicleJourneyTimingLink id="67">
         <JourneyPatternTimingLinkRef>11</JourneyPatternTimingLinkRef>
         <RunTime>PT1M10S</RunTime>
      </VehicleJourneyTimingLink>
      <VehicleJourneyTimingLink id="68">
         <JourneyPatternTimingLinkRef>12</JourneyPatternTimingLinkRef>
         <RunTime>PT1M50S</RunTime>
      </VehicleJourneyTimingLink>
      <VehicleJourneyTimingLink id="69">
         <JourneyPatternTimingLinkRef>13</JourneyPatternTimingLinkRef>
         <RunTime>PT0M32S</RunTime>
      </VehicleJourneyTimingLink>
      <VehicleJourneyTimingLink id="70">
         <JourneyPatternTimingLinkRef>14</JourneyPatternTimingLinkRef>
         <RunTime>PT0M36S</RunTime>
      </VehicleJourneyTimingLink>
      <VehicleJourneyTimingLink id="71">
         <JourneyPatternTimingLinkRef>15</JourneyPatternTimingLinkRef>
         <RunTime>PT1M6S</RunTime>
      </VehicleJourneyTimingLink>
      <VehicleJourneyTimingLink id="72">
         <JourneyPatternTimingLinkRef>16</JourneyPatternTimingLinkRef>
         <RunTime>PT1M46S</RunTime>
      </VehicleJourneyTimingLink>
      <VehicleJourneyTimingLink id="74">
         <JourneyPatternTimingLinkRef>18</JourneyPatternTimingLinkRef>
         <RunTime>PT1M19S</RunTime>
      </VehicleJourneyTimingLink>
      <VehicleJourneyTimingLink id="75">
         <JourneyPatternTimingLinkRef>19</JourneyPatternTimingLinkRef>
         <RunTime>PT0M38S</RunTime>
      </VehicleJourneyTimingLink>
      <VehicleJourneyTimingLink id="76">
         <JourneyPatternTimingLinkRef>20</JourneyPatternTimingLinkRef>
         <RunTime>PT1M3S</RunTime>
      </VehicleJourneyTimingLink>
      <VehicleJourneyTimingLink id="77">
         <JourneyPatternTimingLinkRef>21</JourneyPatternTimingLinkRef>
      </VehicleJourneyTimingLink>
      <VehicleJourneyTimingLink id="78">
         <JourneyPatternTimingLinkRef>22</JourneyPatternTimingLinkRef>
         <RunTime>PT0M33S</RunTime>
      </VehicleJourneyTimingLink>
      <VehicleJourneyTimingLink id="79">
         <JourneyPatternTimingLinkRef>23</JourneyPatternTimingLinkRef>
         <RunTime>PT2M27S</RunTime>
      </VehicleJourneyTimingLink>
      <VehicleJourneyTimingLink id="80">
         <JourneyPatternTimingLinkRef>24</JourneyPatternTimingLinkRef>
         <RunTime>PT1M22S</RunTime>
      </VehicleJourneyTimingLink>
      <VehicleJourneyTimingLink id="81">
         <JourneyPatternTimingLinkRef>25</JourneyPatternTimingLinkRef>
         <RunTime>PT2M6S</RunTime>
      </VehicleJourneyTimingLink>
      <VehicleJourneyTimingLink id="82">
         <JourneyPatternTimingLinkRef>26</JourneyPatternTimingLinkRef>
         <RunTime>PT0M41S</RunTime>
      </VehicleJourneyTimingLink>
      <VehicleJourneyTimingLink id="83">
         <JourneyPatternTimingLinkRef>27</JourneyPatternTimingLinkRef>
         <RunTime>PT0M39S</RunTime>
      </VehicleJourneyTimingLink>
      <VehicleJourneyTimingLink id="84">
         <JourneyPatternTimingLinkRef>28</JourneyPatternTimingLinkRef>
         <RunTime>PT0M31S</RunTime>
      </VehicleJourneyTimingLink>
      <VehicleJourneyTimingLink id="85">
         <JourneyPatternTimingLinkRef>29</JourneyPatternTimingLinkRef>
         <RunTime>PT0M41S</RunTime>
      </VehicleJourneyTimingLink>
      <VehicleJourneyTimingLink id="86">
         <JourneyPatternTimingLinkRef>30</JourneyPatternTimingLinkRef>
      </VehicleJourneyTimingLink>
   </VehicleJourney>
</TransXChange>

1 Ответ

0 голосов
/ 23 апреля 2020

Вместо анализа XML заранее жестко запрограммированным NodeName, который может измениться, как вы указали, просто перебрать все имена узлов и извлечь нужные ячейки. Ниже разбирает весь документ на первые две строки.

Кроме того, для передового опыта избегайте использования Select, ActiveSheet, ActiveWorkbook и др. c. См. Как избежать использования Select в Excel VBA .

Public Function XMLDupCheck()
    Dim xmlDoc      As MSXML2.DOMDocument60
    Dim xmlNodeList As MSXML2.IXMLDOMNodeList

    Dim i As Integer
    Dim var As Variant
    Dim strPathToXMLFile As String

    ' INITIALIZE AND LOAD XML DOC
    Set xmlDoc = New MSXML2.DOMDocument60
    xmlDoc.async = False

    strPathToXMLFile = (Sheet1.[addr] & "308_AKT_PK_306_20200418.xml")
    xmlDoc.validateOnParse = True

    If Not xmlDoc.Load(strPathToXMLFile) Then
        MsgBox "Problem"
        Exit Function
    End If

    ' RETURN LIST OF ALL ELMENTS
    Set xmlNodeList = xmlDoc.SelectNodes("/*//*")         ' ALL ELEMENTS SKIPS ROOT
    'Set xmlNodeList = xmlDoc.getElementsByTagName("*")   ' ALL ELEMENTS

    ' ASSIGN WORKSHEET
    With Worksheets("Map")
        i = 1

        ' PARSE ALL NODE NAME AND TEXT TO CELLS
        For Each var In xmlNodeList
            .Cells(1, i) = var.SelectSingleNode("*").nodeName
            .Cells(2, i) = var.SelectSingleNode("*").Text

            i = i + 1
        Next var
    End With
End Function

Выход

Excel Output

Если вы хотите исключить некоторые узлы, включите If или Select Case logi c:

For Each var In xmlNodeList
    Select Case var.nodeName

        Case "VehicleJourney", "VehicleJourneyTimingLink", "JourneyPatternTimingLinkRef", "RunTime"

        Case Else
            .Cells(1, i) = var.nodeName
            .Cells(2, i) = var.Text
            i = i + 1
    End Select
Next var
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...