VBScript,MSXML和命名空间

Xet*_*ius 5 xml vbscript xpath msxml namespaces

给出以下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>
Run Code Online (Sandbox Code Playgroud)

我试图在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
Run Code Online (Sandbox Code Playgroud)

但它找不到RedirectUrl节点,因此当我尝试获取.text属性时没有任何内容.我究竟做错了什么

Tom*_*lak 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")
Run Code Online (Sandbox Code Playgroud)

另一方面 - 我会尝试将受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
Run Code Online (Sandbox Code Playgroud)

看 - 没On Error Resume Next必要.