【发布时间】:2021-05-24 17:28:48
【问题描述】:
我在尝试从以下 XML 中获取 ErrorCode 和 ErrorDescription 的值时遇到了很多困难:
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
<ActionResponse xmlns="http://tempuri.org/">
<ActionResult xmlns:a="http://schemas.datacontract.org/2004/07/RL.Common.CommonTypes" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<a:ErrorCode>1</a:ErrorCode>
<a:ErrorDescription>General Error</a:ErrorDescription>
</ActionResult>
</ActionResponse>
</s:Body>
</s:Envelope>
尝试了以下方法,它正在工作,但在我看来,这种工作方式很糟糕:
cls
$res = [xml]@'
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
<ActionResponse xmlns="http://tempuri.org/">
<ActionResult xmlns:a="http://schemas.datacontract.org/2004/07/RL.Common.CommonTypes" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<a:ErrorCode>1</a:ErrorCode>
<a:ErrorDescription>General Error</a:ErrorDescription>
</ActionResult>
</ActionResponse>
</s:Body>
</s:Envelope>
'@
$XPath = "/ns:Envelope/ns:Body"
[xml]$xml = $res
$namespace = $xml.DocumentElement.NamespaceURI
$ns = New-Object System.Xml.XmlNamespaceManager($xml.NameTable)
$ns.AddNamespace("ns", $namespace)
$ns.AddNamespace("nsa", "http://tempuri.org/")
$ns.AddNamespace("nsb", "http://tempuri.org/")
$product = $xml.SelectSingleNode($XPath, $ns)
Write-Host $product
#exit
$XPath = "/ns:Envelope/ns:Body"
[xml]$xml = $res
$namespace = $xml.DocumentElement.NamespaceURI
$ns = New-Object System.Xml.XmlNamespaceManager($xml.NameTable)
$ns.AddNamespace("ns", $namespace)
$product = $xml.SelectSingleNode($XPath, $ns)
#Write-Host $product.InnerXml
#$newres = [xml]@'
#<ActionResponse xmlns="http://tempuri.org/"><ActionResult xmlns:a="http://schemas.datacontract.org/2004/07/RL.Common.CommonTypes" xmlns:i="http://www.w3.org/2001/XMLS
#chema-instance"><a:ErrorCode>1</a:ErrorCode><a:ErrorDescription>General Error</a:ErrorDescription></ActionResult></ActionResponse>
#'@
[xml]$newres = $product.InnerXml
$XPath = "/ns:ActionResponse"
[xml]$xml = $newres
$namespace = $xml.DocumentElement.NamespaceURI
$ns = New-Object System.Xml.XmlNamespaceManager($xml.NameTable)
$ns.AddNamespace("ns", $namespace)
$product = $xml.SelectSingleNode($XPath, $ns)
$XPath = "/ns:ActionResult"
[xml]$xml = $product.InnerXml
$namespace = $xml.DocumentElement.NamespaceURI
$ns = New-Object System.Xml.XmlNamespaceManager($xml.NameTable)
$ns.AddNamespace("ns", $namespace)
$product = $xml.SelectSingleNode($XPath, $ns)
Write-Host "ErrCode: ",$product.ErrorCode ," ErrDesc: ",$product.ErrorDescription
Write-Host $product.ErrorCode, $product.ErrorDescription
我猜难以获取值的原因是这里使用的名称空间(几个) 提前感谢所有帮助。
【问题讨论】:
-
如果你想使用 XPATH 但忽略命名空间,那么你可以使用 XPATH
local-name()函数。$XPath = '//*[local-name()="ActionResult"]'. -
我认为我不能忽略名称空间,因为这个 xnl 是运行 Web 服务的结果,除非我在这里遗漏了一些东西..
标签: xml powershell namespaces