1

Say I have some xml. How to get the attribute value using VB?

1
  • Maybe you should give more detail? How do you load the XML now, or are you doing anything with the XML right now at all? Commented Jul 6, 2010 at 2:29

2 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

Comments

0

You might also want to have a look at this:

http://www.w3schools.com/XPath/xpath_syntax.asp

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.