如何在 VBA 中使用 DOMDocument 解析 XML

问题描述 投票:0回答:1

如何获取此 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
vba xml dom soap
1个回答
2
投票

您忘记考虑名称空间。所以添加行

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
© www.soinside.com 2019 - 2024. All rights reserved.