如何使用PowerShell更改XML Element属性的值?

use*_*904 28 xml powershell powershell-2.0

我试图从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>
Run Code Online (Sandbox Code Playgroud)

从上面的例子我想打印分支属性,然后想要在所有整个XML中使用一个值(如纽约)更改它,并使用下面的代码来执行该操作

       $xml=New-Object XML

      $xml.Load("C:\FE6Work.xml")

      $node=$xml.SelectNodes("/office/staff")

      write-output $node.branch
      $node.branch="New York"
Run Code Online (Sandbox Code Playgroud)

但得到一个错误说明无法找到该元素.

有人可以帮忙吗?

Pet*_*erK 39

请尝试以下方法:

$nodes = $xml.SelectNodes("/office/staff");
foreach($node in $nodes) {
    $node.SetAttribute("branch", "New York");
}
Run Code Online (Sandbox Code Playgroud)

这将迭代SelectNodes()返回的所有节点并修改每个节点.

  • 老兄,这真棒!我写了这个大花哨的UI,并认为我不得不废弃整个事情,因为我无法弄清楚如何更改XML值.+1,太棒了,你摇滚. (2认同)

zda*_*dan 12

您可以直接在[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}                                                         
Run Code Online (Sandbox Code Playgroud)