给定以下 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 属性时什么也没有。我做错了什么
最佳答案
您使用了错误的命名空间声明。
在你的 XML 中你有
http://www.w3.org/2003/05/soap-envelope
but in your Script, you use
http://schemas.xmlsoap.org/soap/envelope/
This works for me:
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
语句影响的行保持在绝对 最低限度。理想情况下,它仅对单个关键行有效(或者您将关键部分包装在 Sub
中)。这使得调试很多更容易。
例如,您在 Set redirectUrl = ...
中缺少 Set
语句。当 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
。
关于xml - VBScript、MSXML 和命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1199739/