VBA Excel SelectSingleNode 语法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20032610/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 00:30:20  来源:igfitidea点击:

VBA Excel SelectSingleNode syntax

xmlexcel-vbaxpathvbaexcel

提问by user429400

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

我正在使用以下代码获取 xml 中“DistanceUnit”元素的值:

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:

调试时,我看到 curNode 什么都没有。我不明白为什么。当我使用迭代代码时,它似乎工作正常:

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...

我不想使用迭代代码,因为我知道元素的确切 xpath...

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

此代码也有效,但我只想使用 xpath:

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

Thanks, Li

谢谢,李

My xml:

我的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>

采纳答案by Joe

Try specifying a namespace prefix for your default namespace declaration (see this KB articlefor 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")