【问题标题】:Is it possible to loop through childnode with a specific tag name in XML with VBA?是否可以使用 VBA 在 XML 中使用特定标签名称循环子节点?
【发布时间】:2017-08-08 19:49:55
【问题描述】:

例如,我想只循环通过标签名为“result”的“test”的子节点。

  <test>

    <result>
    </result>
    <memo1>
    </memo1>

    <result>
    </result>

    <memo2>
    </memo2>

    <result>
    </result>

    <memo3>
    </memo3>


  </test>

我认为this 可能会提供我想要的东西。但是,我并不完全了解它是如何工作的(如果它确实提供了我想要的东西)。

【问题讨论】:

  • 你想做什么?您提供的 xml 数据非常有限。请放入另一个级别的子节点,以便可以使用您的数据编写更具信息性的答案。

标签: xml vba excel


【解决方案1】:

这是一个使用 XML 数据的示例。我相当确定您的 XML 文件必须在第一行包含 &lt;?xml version='1.0'?&gt;。但除此之外,它是这样工作的:

Sub testXMLLoop()
    Dim xml As String
    xml = "<?xml version='1.0'?>" & _
    vbCrLf & "  <test>" & _
    vbCrLf & "    <result>" & _
    vbCrLf & "    </result>" & _
    vbCrLf & "    <memo1>" & _
    vbCrLf & "    </memo1>" & _
    vbCrLf & "    <result>" & _
    vbCrLf & "    </result>" & _
    vbCrLf & "    <memo2>" & _
    vbCrLf & "    </memo2>" & _
    vbCrLf & "    <result>" & _
    vbCrLf & "    </result>" & _
    vbCrLf & "    <memo3>" & _
    vbCrLf & "    </memo3>" & _
    vbCrLf & "  </test>"
    Dim xmlDoc As Object
    Set xmlDoc = CreateObject("Msxml2.DOMDocument.6.0")
    xmlDoc.LoadXML xml
    'xmlDoc.Load "file\path\to\books.xml"
    If (xmlDoc.parseError.ErrorCode <> 0) Then
        Dim myErr As Object
        Set myErr = xmlDoc.parseError
        Debug.Print "You have error " + myErr.reason
    Else
        Dim objNodeList As Object
        Set objNodeList = xmlDoc.getElementsByTagName("test")
        Dim oTestList, oChild As Object
        For Each oTestList In objNodeList
            For Each oChild In oTestList.ChildNodes
                if oChild.nodeName = "result" then
                    'Do stuff with oChild
                    Debug.Print oChild.nodeTypedValue
                end if
            Next
        Next
    End If
End Sub

【讨论】:

    猜你喜欢
    • 2015-10-03
    • 1970-01-01
    • 1970-01-01
    • 2016-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-28
    • 1970-01-01
    相关资源
    最近更新 更多