我正在使用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
执行上述代码时出现错误。有人可以帮我解决这个问题。谢谢!
答案 0 :(得分:3)
在xml样本中,Name
和Address
是Details
的子代。以下代码重新运行Details
和Dept
:
For Each node In mainnode
Dim child As Object
For Each child In node.ChildNodes
Debug.Print child.BaseName
Next child
Next node
如果您想要Details
和Dept
的孩子,则需要更深入一点:
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”未显示。我的代码中缺少什么吗? ?