繁体   English   中英

根据条件使用Powershell在xml中附加属性

[英]Append a attribute in xml using Powershell based on a condition

下面是我的 XML 代码:

<office>
<staff branch=" Culver City" Type="Implementation">
    <employee >
        <Name>Geoff Lyle</Name>
        <function>Consultant</function>
        <age>40</age>
    </employee>

    <employee>
        <Name>Kevin</Name>
        <function>Consultant</function>
        <age>39</age>
    </employee>

    <employee>
        <Name>David</Name>
        <function>Consultant</function>
        <age>22</age>
    </employee>

</staff>
</office>

如果年龄超过 40 岁,我如何使用 powershell 将“解雇”属性附加到。我尝试编写如下所示的脚本。 有人可以帮我解决我的语法吗

$xml = New-Object XML
$xml.Load("C:\Users\rparpani\Desktop\test.xml")

$nodes = $xml.SelectNodes("/office/staff/employee")
$node2 = $xml| Select - XML -XPath "//employee[@age]"
foreach($node in $nodes)
{
if($node2 ge 40){
$node.SetAttribute("status", "fired");
}

}

$xml.Save("C:\Users\rparpani\Desktop\test.xml")

我将使用 XPath 按age值过滤 XML 节点:

$xmlPath = "C:\Users\rparpani\Desktop\test.xml"
$xml = New-Object XML
$xml.Load($xmlPath)

$nodes = $xml.SelectNodes("/office/staff/employee[number(age) >= 40]")
foreach ($node in $nodes) {
  $node.SetAttribute("status", "fired")
}

$xml.Save($xmlPath)

如果你这样做了,你的方法会起作用 if if ($node.age -ge 40) { ... } ,但是当我们无论如何用 XPath 检索节点时,为什么不使用 XPath 过滤节点。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM