Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use XPath to retrieve attribute value for specific attribute

In PowerShell I'm trying to retrieve the value of an attribute using XPath. In the example below, I'd like to get the value of "name" for the category of "hi," which would be "new test."

Example code shows:

<Report name="test" category="thisone">
  <String>test</String>
  <String>test2</String>
  <Report name="new test" category="hi">
    <String>hello</String>
    <String>hi again</String>
  </Report>
</Report>

This is what I have:

Select-Xml -XPath "//Report[@name='test']/Report" | Select name |
    Out-File "result.txt" 

My results are:

name
----

I don't really need to specify the category attribute because that <Report> tag will always be right after the first <Report> tag, so that's why I thought it would be easier to use XPath.

like image 214
Awsmike Avatar asked Mar 20 '26 10:03

Awsmike


1 Answers

You need to expand the node first. Select-XML is providing the object. If you do :

Select-Xml -Xml $XML -XPath "//Report[@name='test']/Report"

you will get

Node : Report

Path : InputStream

Pattern : //Report[@name='test']/Report

Once you expand "Node" you will get a bunch more properties

Select-Xml -Xml $XML -xPath "//Report[@name='test']/Report" | Select-Object –ExpandProperty “node” | select *

name : new test

category : hi

String : {hello, hi again}

LocalName : Report

...etc...etc

Full Concept Below

[xml]$XML = @"
<Report name="test" category="thisone">
 <String>test</String>
 <String>test2</String>
  <Report name="new test" category="hi">
  <String>hello</String>
  <String>hi again</String>
  </Report>
</Report>
"@

Select-Xml -Xml $XML -xPath "//Report[@name='test']/Report" | Select-Object –ExpandProperty “node” | select name
like image 195
ArcSet Avatar answered Mar 23 '26 05:03

ArcSet