Reputation: 79
I am working to build a Power shell script that reads a XML file and extracts the values from the nodes to make further calculations. How could I extract the node values to variables?
I have written code using XMLDOC in PS to read the file and extract the values in Power shell. I am able to get the attribute value of a single node. I am not able to extract the node value which has attributes too and there are multiple occurrences of the node.
Test.xml
<abc>
<body>
<Rows Count="02">
<Row>
<a ID="1">Name1</a>
<a ID="2">Naresh</a>
<a ID="3">Arvind</a>
</Row>
<Row>
<a ID="1">Name2</a>
<a ID="2">Sathish</a>
<a ID="3">Kannan</a>
</Row>
</Rows>
</body>
<abc>
Code
[xml]$XmlDocument = Get-Content E:\Desktop\Test.xml
$nodes = $XmlDocument.SelectNodes('//Rows')
$A = $nodes.GetAttribute("count")
if ($A -eq '02')
{
$B = $XmlDocument.abc.Body.Rows.ROW.a | Where-Object {$_.ID -eq '2'}
}
Expected Result
Variable A should get "02"(only value) and "Naresh","Sathish" (only values) should be stored in 2 different variables
Actual Result
Variable A gets "02" - it is working both "Naresh" and "Sathish" are stored in Variable B but stored with the IDs and headers.
Upvotes: 0
Views: 4769
Reputation: 4119
[xml] $str = @'
<abc>
<body>
<Rows Count="02">
<Row>
<a ID="1">Name1</a>
<a ID="2">Naresh</a>
<a ID="3">Arvind</a>
</Row>
<Row>
<a ID="1">Name2</a>
<a ID="2">Sathish</a>
<a ID="3">Kannan</a>
</Row>
</Rows>
</body>
</abc>
'@
$a = $str.abc.body.Rows.Row.a | Where-Object {$_.ID -eq '2'} | Select-Object -ExpandProperty '#text'
Use the Select-Object property and you will be having only Naresh & Sathish in output.
Upvotes: 3