使用VBA获取XML中的所有属性和值

时间:2018-07-31 13:16:29

标签: xml excel vba excel-vba

我正在使用VBA从XML父节点获取所有属性和值。

这是XML:

<Elements>
   <Details>
      <Name>ABC</Name>
      <Address>123ABC</Address>
   </Details>   
   <Dept>
      <Deptname>IT</Deptname>
      <ID>A123</ID>
   </Dept>  
</Elements>

这是我在VBA中使用的代码

sub test() 
    Dim XMLFile As Object
    Dim XMLFileName As String
    Set XMLFile = CreateObject("Microsoft.XMLDOM")

    XMLFileName = "C:\Users\Input.xml"
    XMLFile.async = False
    XMLFile.Load (XMLFileName)
    XMLFile.validateOnParse = False

    Dim mainnode As Object
    Dim node As Object

    Set mainnode = XMLFile.SelectNodes("//Elements")

    For Each node In mainnode
        Dim child As Variant
        For Each child In node.ChildNodes
            Debug.Print child.Name
        Next child
    Next node
End sub

这是我期望的输出。

Details
Name
Address
Dept
deptname
ID

执行上述代码时出现错误。有人可以帮我解决这个问题。谢谢!

2 个答案:

答案 0 :(得分:3)

样本中,NameAddressDetails的子代。以下代码重新运行DetailsDept

For Each node In mainnode
    Dim child As Object
    For Each child In node.ChildNodes
        Debug.Print child.BaseName
    Next child
Next node

如果您想要DetailsDept的孩子,则需要更深入一点:

For Each node In mainnode
    Dim child As Object
    For Each child In node.ChildNodes
        Debug.Print child.BaseName
        Dim kiddo As Object
        For Each kiddo In child.ChildNodes
            Debug.Print kiddo.BaseName
        Next kiddo
    Next child
Next node

答案 1 :(得分:0)

我可以通过以下代码获得预期的结果

For Each node In mainnode
Dim child As Object
'For i = 0 To node.ChildNodes.Length - 1
i = 0
    For Each child In node.ChildNodes


            Debug.Print child.BaseName
            Worksheets("sheet1").Range("C" & i + 1).Value = child.BaseName

            'i = i + 1

            Dim kiddo As Object
                For Each kiddo In child.ChildNodes
                Debug.Print kiddo.BaseName
                Worksheets("sheet1").Range("D" & i + 1).Value = kiddo.BaseName
                i = i + 1
                Next kiddo
            Next child
            Next node

当我的XML仅包含不带标签的属性时,上面的代码没有选择节点。

更新的XML:      <Elements> <Details> <Name>ABC</Name> <Address>123ABC</Address> </Details>
<Dept num = "123" > <Deptname>IT</Deptname> <ID>A123</ID> <ID1>A123</ID1> </Dept> </Elements>

子节点:“ num”未显示。我的代码中缺少什么吗? ?