2

I have some 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>

Can't deal with it because of namespaces. Trying a lot, but not working.

[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

If

$xmlvalue = $stuff.SelectSingleNode($xpath,'SOAP')

Error - Unable to find overload for "SelectSingleNode"

How to make that xpath query work with namespaces?

1 Answer 1

2

I don't see your $xmlns defined. This works:

[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)

Note: You can also access the nodes like properties with PowerShell:

$stuff.DocumentElement.Body.P2MessageServiceStatus.CONNECTION
Sign up to request clarification or add additional context in comments.

5 Comments

if i use $stuff.SelectSingleNode($xpath,$namespace) its not work at all. If $stuff.SelectSingleNode($xpath,$namespaceMgr) it returns value but also i got exception 'cant find reload for SelectSingleNode and 2 methods...' ... is it normal ?
omg i got that exception on work pc but not on my server... it works..thank you a lot
if i see variable $namespaceMgr i will see 3 of them - xmlns,xml, SOAP. could it be an errors reason?
My xml to parse starts with <?xml version="1.0"?> <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> <s:Body> <u:GetInfoResponse xmlns:u="urn:dslforum-org:service:WLANConfiguration:1">.... How can I parse it? This works: $xml=[xml]$xml.Content;Write-Host $xml.xml which gives version="1.0" but $xml.DocumentElement prints nothing. Do I need a namespacemanager and $xpath?
Instead of $stuff.SelectSingleNode($xpath,$ns) you mean $stuff.SelectSingleNode($xpath,$namespace)?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.