Search code examples
xmlpowershellpowershell-2.0powershell-3.0powershell-4.0

How to extract the value of xml node to a variable in powershell?


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.


Solution

  • [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