Powershell: XPath can't select when element has "xmlns" tag?

I have a very simple xml like 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 the Folder item:

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

      

It outputs:

#text                                                                                                                                                                            
-----                                                                                                                                                                            
today                                                                                                                                                                            
tomorrow                                                                                                                                                                         
yesterday 

      

No problems. But if I change the xml file, add "xmlns =" ​​http://schemas.microsoft.com/developer/msbuild/2003 "to" First "as shown 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 doesn't output anything. What for? How do I change my powershell script to support this xmlns?

Many thanks.

+3


source to share


1 answer


What you added is the default namespace. Unlike a prefixed namespace, descendant elements implicitly inherit the parent's default namespace, unless otherwise specified (using an explicit prefix or a local default namespace pointing to a different URI).

To select an item in a namespace, you need to define a prefix that points to the namespace URI and use that prefix correctly in your XPath, for example:



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

      

+4


source







All Articles