如何使用 PowerShell 更改 XML 元素属性的值? [英] How to change the value of XML Element attribute using PowerShell?
本文介绍了如何使用 PowerShell 更改 XML 元素属性的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从 XML 标记访问和更改特定属性
I am trying to access and change the particular attribute from XML tag
XML:
<office>
<staff branch="Hanover" Type="sales">
<employee>
<Name>Tobias Weltner</Name>
<function>management</function>
<age>39</age>
</employee>
<employee>
<Name>Cofi Heidecke</Name>
<function>security</function>
<age>4</age>
</employee>
</staff>
<staff branch="London" Type="Technology">
<employee>
<Name>XXXX</Name>
<function>gement</function>
<age>39</age>
从上面的示例中,我想打印分支属性,然后想在整个 XML 中使用一个值(例如 New York)更改它,并使用以下代码来执行此操作
From the above example I want to print branch attribute and then want to change it with one value such as New York in all the whole XML and using below code to do that
$xml=New-Object XML
$xml.Load("C:\FE6Work.xml")
$node=$xml.SelectNodes("/office/staff")
write-output $node.branch
$node.branch="New York"
但是得到一个错误,指出找不到元素.
But get an error stating can't find the element.
有人可以帮忙吗?
推荐答案
尝试以下操作:
$nodes = $xml.SelectNodes("/office/staff");
foreach($node in $nodes) {
$node.SetAttribute("branch", "New York");
}
这将遍历 SelectNodes() 返回的所有节点并修改每个节点.
This will iterate through all nodes returned by SelectNodes() and modify each one.
这篇关于如何使用 PowerShell 更改 XML 元素属性的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文