Windows 基于条件使用Powershell在xml中追加属性
下面是我的XML代码:Windows 基于条件使用Powershell在xml中追加属性,windows,powershell,Windows,Powershell,下面是我的XML代码: <office> <staff branch=" Culver City" Type="Implementation"> <employee > <Name>Geoff Lyle</Name> <function>Consultant</function> <age>40</age> </empl
<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>
我将使用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($node.age-ge 40){…}
,那么您的方法会起作用,但是在我们使用XPath检索节点时,为什么不使用XPath过滤节点呢。谢谢@Tomalak。我只是需要语法方面的帮助。反馈非常有用
$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)