xml - VBA Excel SelectSingleNode 语法

标签 xml excel xpath vba

我使用以下代码来获取 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")

调试时我发现 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

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

这段代码也可以工作,但我只想使用 xpath:

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

谢谢, 李

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

最佳答案

尝试为默认命名空间声明指定命名空间前缀(有关详细信息,请参阅 this KB article):

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")

关于xml - VBA Excel SelectSingleNode 语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20032610/

相关文章:

arrays - 当源表只有一行时,使用 MATCH 的数组公式不会给出结果

excel - 从合并单元格中删除时类型不匹配 13 错误 - VBA

java - 使用 Java for 循环中的 Xpath

c# - 我如何列出 XML 中的所有 namespace ?

xml - XPath是否具有最大值?

excel - 如何进行有条件的 Vlookup

xml - 如何使用 ConvertTo-Xml 和 Select-Xml 加载或读取 XML 文件?

php - 在 PHP 中从另一台服务器读取 xml 文件的方法有多少种?

javascript - jQuery 中的 XML 请求被忽略

java - 检查相同的文本是否出现在 2 个不同的 xpath 下