xmlpowershellnamespacesselectsinglenode

Select XML nodes from a namespace using Powershell


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.


Solution

  • I don't understand the problem. The namespaces doesn't matter here because your xml-sample doesn't contain prefixed elements or a default namespace. You can access the element like this:

    $xml.SelectNodes("//AutoIndexEnabled")
    

    or

    $xml.SelectNodes("//setting[@name='KMSettings']//AutoIndexEnabled")
    

    Output:

    #text
    -----
    false
    
    PS> $xml.SelectNodes("//AutoIndexEnabled").InnerText
    false