0

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.

1 Answer 1

3
[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.

enter image description here

Sign up to request clarification or add additional context in comments.

2 Comments

Can we extract "Naresh" and "Sathish" in two different variables? $A = Naresh $B = Sathish Could we use where-object for the first fields?
I used an array to split the values to two variables

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.