Select XML nodes from a namespace using Powershell

kr0me picture kr0me · May 13, 2016 · Viewed 18.2k times · Source

I have the following xml:

<?xml version="1.0" encoding="utf-8"?>
<userSettings>
  <setting name="TelephonyServerHost">
    <value>sipserver.domain.local</value>
  </setting>
  <setting name="SipServerFqdn">
    <value>sipserver.domain.local</value>
  </setting>
  <setting name="WebServicesHost">
    <value>websvc.domain.local</value>
  </setting>
  <setting name="KMSettings">
    <value>
      <KMIndexSettings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
        <AutoIndexEnabled>false</AutoIndexEnabled>
     </KMIndexSettings>
    </value>
  </setting>
</userSettings>

I am able to retrieve the values of the setting elements using xpath but I cannot figure out the correct syntax for querying the AutoIndexEnabled element using the namespace.

This works as expected for reading the KMSettings or other nodes which do not have a namespace:

$xml = New-Object -TypeName 'System.XML.XMLDocument'
$xml.Load($xmlFilePath)
$node = $xml.SelectSingleNode("//userSettings/setting[@name='KMSettings']")

But I can't figure out the syntax on how to query the AutoIndexEnabled element.

Answer

Martin Brandl picture Martin Brandl · May 13, 2016

Within PowerShell you can access XML nodes like properties, so this works:

($xml.DocumentElement.setting | ? name -eq 'KMSettings').value.KMIndexSettings.AutoIndexEnabled

And here is a working XPATH solution:

[string]$xpath="//userSettings/setting[@name='KMSettings']/value/KMIndexSettings/AutoIndexEnabled"       
$xml.SelectSingleNode($xpath)