如何在PowerShell中将xml节点的值提取到变量?

问题描述 投票:0回答:1

我正在构建一个Power shell脚本,该脚本读取XML文件并从节点中提取值以进行进一步的计算。我怎样才能将节点值提取到变量?

我在PS中使用XMLDOC编写代码来读取文件并在Power shell中提取值。我能够获得单个节点的属性值。我无法提取具有属性的节点值,并且节点有多次出现。

嗯测试

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

   [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'}
    }

预期结果

变量A应该得到“02”(只有值)和“Naresh”,“Sathish”(只有值)应该存储在2个不同的变量中

实际结果

变量A得到“02” - 它正在工作“Naresh”和“Sathish”存储在变量B中,但存储有ID和标题。

xml powershell powershell-v2.0 powershell-v3.0 powershell-v4.0
1个回答
1
投票
[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'

使用Select-Object属性,输出中只有Naresh和Sathish。

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.