5

给定以下 XML:

<?xml version="1.0"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <soap:Body>
        <GetMsisdnResponse xmlns="http://my.domain.com/">
            <GetMsisdnResult>
                <RedirectUrl>http://my.domain.com/cw/DoIdentification.do2?sessionid=71de6551fc13e6625194</RedirectUrl>
            </GetMsisdnResult>
        </GetMsisdnResponse>
    </soap:Body>
</soap:Envelope>

我正在尝试使用 VBScript 中的 XPath 访问 RedirectUrl 元素:

set xml = CreateObject("MSXML2.DOMDocument")
xml.async = false
xml.validateOnParse = false
xml.resolveExternals = false
xml.setProperty "SelectionLanguage", "XPath"
xml.setProperty "SelectionNamespaces", "xmlns:s='http://my.domain.com/' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'"

err.clear
on error resume next
xml.loadXML (xmlhttp.responseText)
if (err.number = 0) then

    redirectUrl = xml.selectSingleNode("/soap:Envelope/soap:Body/s:GetMsisdnResponse/s:GetMsisdnResult/s:RedirectUrl").text
end if

但它无法找到 RedirectUrl 节点,因此当我尝试获取 .text 属性时什么都没有。我究竟做错了什么

4

2 回答 2

10

您使用了错误的命名空间声明。

在您的 XML 中,您有

http://www.w3.org/2003/05/soap-envelope

但是在您的脚本中,您使用

http://schemas.xmlsoap.org/soap/envelope/

这对我有用:

xml.setProperty "SelectionNamespaces", "xmlns:s='http://my.domain.com/' xmlns:soap='http://www.w3.org/2003/05/soap-envelope'"

' ...

Set redirectUrl = xml.selectSingleNode("/soap:Envelope/soap:Body/s:GetMsisdnResponse/s:GetMsisdnResult/s:RedirectUrl")

另一方面,我会尝试将受On Error Resume Next语句影响的行保持在绝对最小值。理想情况下,它仅对单个关键行有效(或者您将关键部分包装在 a 中Sub)。这使调试变得容易得多。

例如,您Set缺少Set redirectUrl = .... 当 On 打开时,这将静默失败Error Resume Next

尝试

' this is better than loadXML(xmlHttp.responseText)
xmlDocument.load(xmlHttp.responseStream)

If (xmlDocument.parseError.errorCode <> 0) Then
  ' react to the parsing error
End If

Xpath = "/soap:Envelope/soap:Body/s:GetMsisdnResponse/s:GetMsisdnResult/s:RedirectUrl"
Set redirectUrl = xml.selectSingleNode(Xpath)

If redirectUrl Is Nothing Then
  ' nothing found
Else
  ' do something
End If

看 - 没有On Error Resume Next必要。

于 2009-07-29T12:07:30.220 回答
3

另请注意,命名空间区分大小写,但至少某些 MSXML 会强制它小写。

所以如果你声明xml.setProperty "SelectionNamespaces", "xmlns:SSS='http://my.domain.com/'"

并尝试xml.selectSingleNode("/SSS:Envelope")它可能会失败。

您将需要使用xml.selectSingleNode("/sss:Envelope").

或者更好地使您的名称空间小写。

于 2014-01-30T09:59:22.370 回答