vik santata
vik santata

Reputation: 3109

Powershell: XPath cannot select when element has "xmlns" tag?

I've got a very simple xml, as below:

<?xml version="1.0" encoding="utf-8"?>
<First>
  <Second>
    <Folder>today</Folder>
    <FileCount>10</FileCount>
  </Second>
  <Second>
    <Folder>tomorrow</Folder>
    <FileCount>90</FileCount>
  </Second>
  <Second>
    <Folder>yesterday</Folder>
    <FileCount>22</FileCount>
  </Second>
</First>

Then I have a powershell script to select "Folder" element:

[xml]$xml=Get-Content "D:\m.xml"
$xml.SelectNodes("//Folder")

It outputs:

#text                                                                                                                                                                            
-----                                                                                                                                                                            
today                                                                                                                                                                            
tomorrow                                                                                                                                                                         
yesterday 

No problem. But if I change the xml file to add "xmlns="http://schemas.microsoft.com/developer/msbuild/2003" to "First" like below:

<?xml version="1.0" encoding="utf-8"?>
<First xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Second>
    <Folder>today</Folder>
    <FileCount>10</FileCount>
  </Second>
  <Second>
    <Folder>tomorrow</Folder>
    <FileCount>90</FileCount>
  </Second>
  <Second>
    <Folder>yesterday</Folder>
    <FileCount>22</FileCount>
  </Second>
</First>

Then, my powershell script outputs nothing. Why? How to change my powershell script to support this xmlns?

Thanks a lot.

Upvotes: 3

Views: 2149

Answers (1)

har07
har07

Reputation: 89325

What you added is default namespace. Unlike prefixed namespace, descendant elements inherit ancestor default namespace implicitly, unless otherwise specified (using explicit prefix or local default namespace that points to different URI).

To select element in namespace, you'll need to define prefix that point to the namespace URI and use that prefix properly in your XPath, for example :

$ns = New-Object System.Xml.XmlNamespaceManager($xml.NameTable)
$ns.AddNamespace("d", $xml.DocumentElement.NamespaceURI)
$xml.SelectNodes("//d:Folder", $ns)

Upvotes: 4

Related Questions