提问人:KAtkinson 提问时间:6/7/2023 最后编辑:KAtkinson 更新时间:6/7/2023 访问量:35
如何在 VBA 中使用 DOMDocument 分析 XML
How to Parse XML Using DOMDocument in VBA
问:
我将如何获取此 XML 文档中下面指示的节点的值。
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Header>
<h:ResponseContext xmlns:h="http://purolator.com/pws/datatypes/v2" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<h:ResponseReference>UserRef</h:ResponseReference>
</h:ResponseContext>
</s:Header>
<s:Body>
<CreateShipmentResponse xmlns="http://purolator.com/pws/datatypes/v2" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ResponseInformation>
<Errors/>
<InformationalMessages i:nil="true"/>
</ResponseInformation>
<ShipmentPIN>
<Value>329035959744</Value> ' <-- This is the node I want the value of
</ShipmentPIN>
<PiecePINs>
<PIN>
<Value>329035959744</Value>
</PIN>
<PIN>
<Value>329035959751</Value>
</PIN>
</PiecePINs>
</CreateShipmentResponse>
</s:Body>
</s:Envelope>
我尝试使用已回答的另一个问题中的信息,但是当我运行代码时它没有返回任何内容。(Excel VBA 从 XML 获取特定节点)
Set response = CreateObject("MSXML2.DOMDocument")
response.SetProperty "SelectionLanguage", "XPath"
response.Async = False
response.validateOnParse = False
response.Load(respPath)
Set nodeXML = xmlDoc.getElementsByTagName("Value")
For i = 0 To nodeXML.Length - 1
Debug.Print nodeXML(i).Text
Next
答:
2赞
zx485
6/7/2023
#1
您忘了考虑命名空间。所以添加这一行
response.setProperty "SelectionNamespaces", "xmlns:pur='http://purolator.com/pws/datatypes/v2'"
并将代码更改为
Set response = CreateObject("MSXML2.DOMDocument")
response.setProperty "SelectionLanguage", "XPath"
response.setProperty "SelectionNamespaces", "xmlns:pur='http://purolator.com/pws/datatypes/v2'"
response.Async = False
response.validateOnParse = False
response.Load(respPath)
Set nodeXML = response.selectNodes("//pur:ShipmentPIN/pur:Value")
For i = 0 To nodeXML.Length - 1
Debug.Print nodeXML(i).Text
Next
评论
response
xmlDoc.getElementsByTagName
Option Explicit