简体   繁体   中英

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.

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)

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

I this particular example, how would you select the value of the attribute with name "xmlns:xsi"?

<value>
  <KMIndexSettings xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ... >
    <AutoIndexEnabled>false</AutoIndexEnabled>
 </KMIndexSettings>
</value>

I would expect to see the output: " http://www.w3.org/2001/XMLSchema-instance "

This is what I'm trying.The colon is throwing off my script. I get the following error: "Unexpected token ':id' in expression or statement."

([xml](gc $files[$i])).contentHaul.constant.typedValue.value.a:id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM