Reputation: 1053
I have the following XML Data in a file "Test1.xml":
<TextValuess>
<TextValues Name="Value1" Override="true" Type="String">
<DEV>Source=DEV;Catalog=DEV_DMT;Integrated Security=SSPI;</DEV>
<INT10>Source=LAB;Catalog=TST_INT10;Integrated Security=SSPI;</INT10>
<INT>Source=LAB1;Catalog=TST_INT1;Integrated Security=SSPI;</INT>
<INT2>Source=LAB10;Catalog=TST_INT12;Integrated Security=SSPI;</INT2>
</TextValues>
<TextValues Name="ENVIRONMENT" Override="true" Type="String">
<DEV>DEV</DEV>
<INT10>INT10</INT10>
<INT>INT1</INT>
<INT2>INT15</INT2>
</TextValues>
</TextValuess>
I want to loop through all the attributes and retrieve the data using PowerShell by passing the parameter which I need to retrieve.
Eg: If I pass the Variable values as INT10 I need only below values something like this:
Name Value ---- ----- Value1 LAB Environment INT10
I Was able to retrieve one of the element values using the below PowerShell commands.
[xml]$XmlDocument = Get-Content D:\Roshan\Test1.xml
$XmlDocument.TextValuess.TextValues[0].INT10
$XmlDocument.TextValuess.TextValues[1].INT10
But the XML tags might grow or reduce each and every time based on file. I need to loop through with the existing data and get the results.
I am not sure how to use foreach
to read all the values in the file.
Upvotes: 0
Views: 154
Reputation: 200373
The most versatile way of selecting data from XML structures is XPath. In your case you'd do something like this:
$child = 'INT10'
$XmlDocument.SelectNodes("//TextValues[./${child}]") | ForEach-Object {
New-Object -Type PSObject -Property @{
'Name' = $_.Name
'Value' = $_.$child
}
} | Select-Object Name, Value
If you want partial information extracted from the child node you need to specify how that's done. For instance:
($_.$child -split ';')[0] -replace '^Source='
Upvotes: 0
Reputation: 1660
You can simply pipe the TextValues
to Select-Object
and specify property names you want values of:
[xml]$XmlDocument = Get-Content D:\Roshan\Test1.xml
$XmlDocument.TextValuess.TextValues | Select-Object Name, INT10
Upvotes: 2