如何使用 PowerShell 更改 XML 元素属性的值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24679454/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to change the value of XML Element attribute using PowerShell?
提问by user3759904
I am trying to access and change the particular attribute from XML tag
我正在尝试从 XML 标记访问和更改特定属性
XML:
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>
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 York)更改它,并使用以下代码来执行此操作
$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.
但是得到一个错误,指出找不到元素。
Can someone please help?
有人可以帮忙吗?
回答by PeterK
Try the following:
请尝试以下操作:
$nodes = $xml.SelectNodes("/office/staff");
foreach($node in $nodes) {
$node.SetAttribute("branch", "New York");
}
This will iterate through all nodes returned by SelectNodes() and modify each one.
这将遍历 SelectNodes() 返回的所有节点并修改每个节点。
回答by zdan
You can access the attributes directly in the [xml]object like this:
您可以[xml]像这样直接在对象中访问属性:
# C:\temp> $xml = [xml](Get-Content C:\FE6Work.xml)
# C:\temp> $xml.office.staff
branch Type employee
------ ---- --------
Hanover sales {Tobias Weltner, Cofi Heidecke}
London Technology {XXXX, Cofi}
# C:\temp> $xml.office.staff | foreach{$_.branch = "New York"}
# C:\temp> $xml.office.staff
branch Type employee
------ ---- --------
New York sales {Tobias Weltner, Cofi Heidecke}
New York Technology {XXXX, Cofi}
回答by Ajish Kumar
if we are taking attribute from console and changing its value ?
如果我们从控制台获取属性并更改其值?
$path=Read-Host -Prompt 'Enter path of xml file'
[xml]$xmldata = get-content "$path"
$tag = Read-Host -Prompt 'Enter tag'
$value = Read-Host -Prompt 'Enter value'
$xmldata.InstallConfig.$tag="$value"
$xmldata.Save($path)

