假设您正在使用 MSXML 库?
以下代码将输出子节点的所有属性值。本例中的 XML 是:-
<?xml version="1.0" encoding="utf-8"?>
<documents>
<document id="12345" created="2002-09-24" owner="Andy" />
</documents>
Run Code Online (Sandbox Code Playgroud)
因此输出将显示 id、created 和owner 的值。
这是代码:-
Dim XML As String
Dim objXML As New MSXML2.DOMDocument
Dim objElem As MSXML2.IXMLDOMElement
Dim objSub As MSXML2.IXMLDOMElement
XML = "<?xml version=""1.0"" encoding=""utf-8""?><documents><document id=""12345"" created=""2002-09-24"" owner=""Andy"" /></documents>"
If Not objXML.LoadXML(XML) Then
Err.Raise objXML.parseError.ErrorCode, , objXML.parseError.reason
End If
Set objElem = objXML.selectSingleNode("//documents")
For Each objSub In objElem.childNodes
Debug.Print objSub.nodeName
If objSub.Attributes.length > 0 Then
For i = 0 To objSub.Attributes.length - 1
Debug.Print objSub.Attributes(i).nodeName & " - " & objSub.Attributes(i).nodeValue
Next i
End If
Next
Run Code Online (Sandbox Code Playgroud)