我是xPath的新手,我正在尝试使用VbScript中的XPath解析下面给出的XML,并且我总是得到null值。
<?xml version="1.0" encoding="UTF-8"?>
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:u="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-
utility-1.0.xsd">
<s:Header>
<o:Security xmlns:o="http://docs.oasis-open.org/wss/2004/01/oasis-
200401-wss-wssecurity-secext-1.0.xsd" s:mustUnderstand="1">
<u:Timestamp u:Id="_0">
<u:Created>2017-03-30T07:08:12.264Z</u:Created>
<u:Expires>2017-03-30T07:13:12.264Z</u:Expires>
</u:Timestamp>
</o:Security>
</s:Header>
<s:Body>
<RegisterAndInviteParticipantResponse
xmlns="http://www.cubonline.com/CubOnline/WebServices/201207">
<RegisterAndInviteParticipantResult xmlns:a="http://schemas.datacontract.org/2004/07/Cub.CubOnline.WebServices.DataContracts" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<a:UserID>322988</a:UserID>
<a:AccessCode>7EBECBBD</a:AccessCode>
<a:LogonUrl>https://uat.sonline.com/Online/Standalone/PLogon.aspx?skin=1379+751&lang=en-GB</a:LogonUrl>
<a:AuthenticatedURL i:nil="true" />
<a:ReportLinksURL>https://uat.sonline.com/Online/Standalone/XViewReportLinks.aspx?key=091d1e-6cd0-45fd-8c81-61ab70107f34&hash=7DDEDAF4CCDD47E5880F086C62E660F8F45B2C9E&skin=234</a:ReportLinksURL>
<a:ParticipantScheduleID>791777</a:ParticipantScheduleID>
</RegisterAndInviteParticipantResult>
</RegisterAndInviteParticipantResponse>
</s:Body>
</s:Envelope>
以下是我的VBScript代码:
Set xmlDoc = Server.CreateObject("Msxml2.DOMDocument.6.0")
xmlDoc.async = False
xmlDoc.resolveExternals = False
xmlDoc.validateOnParse = False
If Not xmlDoc.loadXML(registerParticipantResponse) Then
'//..........do something.
End If
'//=====================================================
'//Try Xpath'ing a few values
'//=====================================================
xmlDoc.setProperty "SelectionLanguage", "XPath"
xmlDoc.setProperty "SelectionNamespaces",
"xmlns:s='http://schemas.xmlsoap.org/soap/envelope/'
xmlns=http://www.cubonline.com/CubOnline/WebServices/201207' xmlns:a='http://schemas.datacontract.org/2004/07/Cub.CubOnline.WebServices.DataContracts' xmlns:i='http://www.w3.org/2001/XMLSchema-instance'"
Dim currNode
Set currNode = xmlDoc.selectSingleNode("//*[local-
name()='RegisterAndInviteParticipantResponse']/@*[local-
name()='RegisterAndInviteParticipantResult']/@*[local-name()='AccessCode']")
accessCode = ""
If Not currNode Is Nothing Then
accessCode = currNode.text
End If
注意:我正在获取访问代码&#39;一片空白。 所以请帮助我如何通过Xpath访问访问代码中的值。
答案 0 :(得分:1)
@
字符应该从XPath中删除,因为它们不是属性而是元素:
"//*[local-name()='RegisterAndInviteParticipantResponse']/
*[local-name()='RegisterAndInviteParticipantResult']/
*[local-name()='AccessCode']"
但是,由于您在代码中设置了用于XPath的命名空间,因此应该更简洁明了:
"//RegisterAndInviteParticipantResponse/
RegisterAndInviteParticipantResult/
a:AccessCode"
以下是@
何时可以与原始文档一起使用的示例(假设o
前缀将在代码中明确绑定):
"/s:Envelope/s:Header/o:Security/@s:mustUnderstand"
通常,当XPath找不到具有指定名称的元素或属性时,它不会返回错误,而是返回空序列。