Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA Excel SelectSingleNode syntax

Tags:

xml

excel

vba

xpath

I'm using the following code to get the value of the "DistanceUnit" element in my xml:

Dim xmlDoc As MSXML2.DOMDocument60
Dim xmlElement As MSXML2.IXMLDOMElement

Set xmlDoc = New MSXML2.DOMDocument60
xmlDoc.async = False
xmlDoc.validateOnParse = False

xmlDoc.LoadXML strResponse
Set xmlElement = xmlDoc.DocumentElement

Set curNode = xmlElement.SelectSingleNode("/Response/ResourceSets/ResourceSet/Resources/Route/DistanceUnit")

When debugging I see that curNode is NOTHING. I don't understand why. When I use an itterative code it seems to work ok:

Set xmlRoot = xmlDoc.DocumentElement
Set xmlChildren = xmlRoot.ChildNodes

For Each xmlTemplate In xmlChildren
    If xmlTemplate.nodeName = "ResourceSets" Then
        MsgBox "found!"
        Exit For
    End If
Next xmlTemplate

I don't want to use itterative code, since I know the exact xpath to the element...

This code work as well, but I just want to use the xpath:

Set curNode = xmlRoot.ChildNodes(6).ChildNodes(0).ChildNodes(1).ChildNodes(0).ChildNodes(2)
MsgBox curNode.Text

Thanks, Li

My xml:

<Response xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.microsoft.com/search/local/ws/rest/v1">
    ....
    <StatusCode>200</StatusCode>
    <StatusDescription>OK</StatusDescription>
    <AuthenticationResultCode>ValidCredentials</AuthenticationResultCode>
    <ResourceSets>
        <ResourceSet>
            <EstimatedTotal>1</EstimatedTotal>
            <Resources>
                <Route>
                    .....
                    <DistanceUnit>Kilometer</DistanceUnit>
                    .....
                </Route>
            </Resources>
        </ResourceSet>
    </ResourceSets>
</Response>
like image 637
user429400 Avatar asked Sep 12 '25 05:09

user429400


1 Answers

Try specifying a namespace prefix for your default namespace declaration (see this KB article for more info):

Set xmlDoc = New MSXML2.DOMDocument60
xmlDoc.async = False
xmlDoc.validateOnParse = False

 xmlDoc.setProperty "SelectionNamespaces", "xmlns:a='http://schemas.microsoft.com/search/local/ws/rest/v1'"

xmlDoc.LoadXML strResponse
Set xmlElement = xmlDoc.DocumentElement

Set curNode = xmlElement.SelectSingleNode("/a:Response/a:ResourceSets/a:ResourceSet/a:Resources/a:Route/a:DistanceUnit")
like image 87
Joe Avatar answered Sep 13 '25 21:09

Joe