首页 > 解决方案 > 使用 PowerShell 获取 XML 值

问题描述

我正在尝试获取<Attribute>,<Condition><Group>标签的值。可以有多个<Attribute>标签,所以我需要分别获取值。

我正在尝试为上述标签准备一个条件。像下面的东西。

if (HireType -eq 'KI' -and HireType1 = 'KI1' ){
  $Groups = 'A,B,C'
} 

我尝试使用 ChildNodes 的 hep 编写代码,但如果有多个标签,它会合并文本。

XML

<UserData>
    <FilterCriteria>
    </FilterCriteria>
    <GroupCriteria>
        <Criteria>
           <Attributes>
              <Attribute>
                 <AttrName>HireType</AttrName>
                 <AttrValue>KI</AttrValue>
              </Attribute>
              <Attribute>
                 <AttrName>HireType1</AttrName>
                 <AttrValue>KI1</AttrValue>
              </Attribute>
              <Condition>and</Condition>
              <Groups>A,B,C</Groups>
           </Attributes>
        </Criteria>
    </GroupCriteria>
</UserData>

代码

[xml] $xml = Get-Content -Path C:\Users\Arun\Desktop\UserData.xml


$xml.UserData.GroupCriteria | foreach {
  $_.Criteria | foreach {
    $_.Attributes | foreach {
          $_.ChildNodes | % {
            $Name = $_.Name
            $Value = $_.InnerText
              write-host "$Name : $Value"
          }
        }
      }
    }

输出

Attribute : HireTypeKI
Attribute : HireType1KI1
Condition : and
Groups : A,B,C

标签: xmlpowershell

解决方案


由于<Attribute>标签的结构不同,您需要处理与其他标签不同的标签:

foreach ($node in $xml.UserData.GroupCriteria.Criteria.Attributes.ChildNodes) {
    switch ($node.Name) {
        'Attribute' {
            $Name = $node.AttrName
            $Value = $node.AttrValue
        }
        default {
            $Name = $node.Name
            $Value = $node.InnerText
        }
    }
    Write-Host "$Name : $Value"
}

推荐阅读