简体   繁体   中英

How to use powershell to get the specific xml element?

Currently we have a xml file such as :

<file>
 <dircetory name="test">
  <directory name="test1">
   <directory name="test2"></directory>
  </directory>
 </directory>
 <directory name="test2">
 </directory>
</file>

The xml structure is not stable, but I need to get the xml node by name attribute

Now I get the "test2" string, and try to get the <directory name="test2"></directory> element, I could use foreach to iterator one by one, but is there any elegent way to do that ?

Thanks

You can use an XPath expression like this to find the relevant nodes:

//*[@name='test2']

Then use the Select-Xml cmdlet and a foreach loop to iterate over the matching nodes:

foreach($result in Select-Xml -Path document.xml -XPath "//*[@name='test2']"){
    # Work with $result.Node in here
}

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