首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >VBA Excel SelectSingleNode语法

VBA Excel SelectSingleNode语法
EN

Stack Overflow用户
提问于 2013-11-17 23:40:32
回答 1查看 20.5K关注 0票数 3

我使用以下代码来获取xml中"DistanceUnit“元素的值:

代码语言:javascript
复制
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什么都不是。我不明白为什么。当我使用迭代代码时,它似乎工作得很好:

代码语言:javascript
复制
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:

代码语言:javascript
复制
Set curNode = xmlRoot.ChildNodes(6).ChildNodes(0).ChildNodes(1).ChildNodes(0).ChildNodes(2)
MsgBox curNode.Text

谢谢,李

我的xml:

代码语言:javascript
复制
<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>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-11-18 00:29:49

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

代码语言:javascript
复制
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")
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20032610

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档