Powershell: XPath cannot select when element has “xmlns” tag?

对着背影说爱祢 提交于 2021-02-09 11:55:55

问题


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.


回答1:


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)


来源:https://stackoverflow.com/questions/31023597/powershell-xpath-cannot-select-when-element-has-xmlns-tag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!