xml - 使用 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
解决方案
由于<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"
}
推荐阅读
- python - 将不同行数的列附加到 DataFrame
- tensorflow - 如何训练一个简单的神经网络来实现中值滤波?
- reactjs - 无法在 useEffect 反应钩子中调度动作
- javascript - 无法从简单的提取中创建 blob
- encryption - PEM_read_X509 函数
- java - NavigationComponents - NavigationDrawer 在 Java 中不起作用 [错误]
- shell - 如何在 python 脚本中运行 postgres 命令并将其写入文件?
- c# - 从存储为“UCS-2 LE BOM”的二进制数组数据中 C# XML 解密
- jenkins - 如何在 Jenkinsfie 中定义类
- security - ADFS 证书更新后无法登录 Jenkins