Say I have some xml. How to get the attribute value using VB?
+2
A:
Assuming you are using the MSXML library?
The following code will output all attribute values of the children nodes. The XML in this case is:-
<?xml version="1.0" encoding="utf-8"?>
<documents>
<document id="12345" created="2002-09-24" owner="Andy" />
</documents>
So the output will show the values for id, created and owner.
Here's the code :-
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
Andy Robinson
2010-07-06 13:46:02