我有一些 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)
Error - need Namespace manager or XsltContext
如果
$xmlvalue = $stuff.SelectSingleNode($xpath,'SOAP')
Error - Unable to find overload for "SelectSingleNode"
如何使 xpath 查询与命名空间一起使用?
最佳答案
我没有看到您定义的 $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
关于xml - powershell、xml 和命名空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37124340/