0

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.

2 Answers 2

2

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

1 Comment

This is working to get the desired result. As the Ansger quirey is much convenient for my requirement, I have selected that as solution.
0

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='

1 Comment

Can you also help me how can I assign Values to a Variable in the ForEach for Each read. Need Something like this $child = 'INT10' $XmlDocument.SelectNodes("//TextValues[./${child}]") | ForEach-Object { New-Object -Type PSObject -Property @{ $Name = $_.Name $Value = $_.$child } } | Select-Object Name, Value

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.