我有一些XML:
<SOAP:Envelope xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP:Body>
<P2MessageServiceStatus>
<CONNECTION>CONNECTION_CONNECTED</CONNECTION>
<ROUTER>ROUTER_CONNECTED</ROUTER>
</P2MessageServiceStatus>
</SOAP:Body>
</SOAP:Envelope>
由于名称空间无法处理它。尝试了很多,但没有工作。
[string]$xpath = '/SOAP:Envelope/SOAP:Body/P2MessageServiceStatus/@CONNECTION'
$wc = New-Object Net.WebClient
[xml]$stuff = $wc.DownloadString($url)
$ns = New-Object Xml.XmlNamespaceManager $stuff.NameTable
$ns.AddNamespace("SOAP", $xmlns)
$xmlvalue = $stuff.SelectSingleNode($xpath, $ns)
错误 - 需要命名空间管理器或XsltContext
如果
$xmlvalue = $stuff.SelectSingleNode($xpath,'SOAP')
错误 - 无法找到“SelectSingleNode”的重载
如何使xpath查询与命名空间一起使用?
答案 0 :(得分:2)
我没有看到您的$xmlns
已定义。这有效:
[string]$xpath='/SOAP:Envelope/SOAP:Body/P2MessageServiceStatus/CONNECTION'
$namespaceMgr = New-Object System.Xml.XmlNamespaceManager $stuff.NameTable
$namespace = $stuff.DocumentElement.NamespaceURI
$namespaceMgr.AddNamespace("SOAP", $namespace)
$stuff.SelectSingleNode($xpath,$ns)
注意:您还可以使用PowerShell
访问属性等节点:
$stuff.DocumentElement.Body.P2MessageServiceStatus.CONNECTION