Trying to get XML element

166 Views Asked by At

Here is a piece of XML file from which I want to extract the IP Address (here 172.31.24.8) using PowerShell code:

<?xml version="1.0"?>
<Configuration xmlns="http://www.tandberg.com/XML/CUIL/2.0" product="Cisco Codec" version="TC7.3.2.14ad7cc" apiVersion="2">
  <SIP item="1">
    <Profile item="1" maxOccurrence="1">
      <Proxy item="1" maxOccurrence="4">
        <Address item="1" valueSpaceRef="/Valuespace/STR_0_255_NoFilt">172.31.24.8</Address>
        <Discovery item="1" valueSpaceRef="/Valuespace/TTPAR_AutoManual">Manual</Discovery>
      </Proxy>
    </Profile>
  </SIP>
</Configuration>

I tried to use Select-Xml as described in other StackOverflow examples, but unsuccessfully so far.

What's the simplest way to achieve this properly?

2

There are 2 best solutions below

0
On BEST ANSWER

I'm not familiar with Powershell, so I cannot help you with the Powershell code, but I think Select-Xml works with XPath expressions.

Given your XML document, and given that you can somehow register a default namespace, the following XPath expression would work:

/Configuration/SIP/Profile/Proxy/Address/text()

If you cannot register a default namespace, perhaps you can register a prefix and a namespace, e.g.

/tb:Configuration/tb:SIP/tb:Profile/tb:Proxy/tb:Address/text()

where tb must correspond to the namespace http://www.tandberg.com/XML/CUIL/2.0. Here is a link that explains how to declare namespaces.


If Select-Xml cannot deal with namespaces, use

/*[local-name() = 'Configuration']/*[local-name() = 'SIP']/*[local-name() = 'Profile']/*[local-name() = 'Proxy']/*[local-name() = 'Address']/text()

and the only result of all those path expressions will be

172.31.24.8
0
On

I finally got it to work.

Here is an example piece of powershell code that returns the wanted output.

$Path="Path\to\my\file.xml"
$Namespace = @{tb="http://www.tandberg.com/XML/CUIL/2.0"}
$xml = Select-Xml -Path $Path -Namespace $Namespace -XPath "//tb:Address"
$xml | foreach {$_.node.InnerXML}

This returns the IP address value.

My original code was not specifying "tb:" in the XPath, that was my mistake.

Thanks for you help !

Regards, Florian