gpt4 book ai didi

xml - VBA Excel SelectSingleNode 语法

转载 作者:行者123 更新时间:2023-12-01 23:21:08 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com