0

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

2
  • What do you mean by "xml structure is not stable"? Commented Jun 18, 2017 at 11:44
  • I mean the <direcotry> maybe has a lot of <directory> sub element Commented Jun 18, 2017 at 11:58

1 Answer 1

1

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.