xml - powershell、xml 和命名空间

标签 xml powershell xpath

我有一些 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/

相关文章:

java - 使用InputStream读取器从/res/xml读取XML文件会产生无效字符/编码数据

创建首选项屏幕时找不到androidx.preference.PreferenceScreen

.net - 通过powershell在iis中限制IP地址和域

xml - 如何使用 SXD-XPath 选择命名空间属性的值?

ios - 如何检查解析的rss变量是否包含swift 2中的确切元素

sql - 为 sp_xml_preparedocument 配置 namespace

powershell - 调用外部可执行文件时抑制 Powershell 错误

powershell - 从 powershell 模块重新签名、重新加载和运行测试功能?

java - 如何在Java中解析具有混合节点和文本的XML?

java - 使用 Jdom/XPath 和 "检索元素