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

问题描述 投票:26回答:3

我试图从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>

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

       $xml=New-Object XML

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

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

      write-output $node.branch
      $node.branch="New York"

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

有人可以帮忙吗?

xml powershell powershell-v2.0
3个回答
34
投票

请尝试以下方法:

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

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


10
投票

您可以直接在[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}                                                         

0
投票

如果我们从控制台获取属性并更改其值?

$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)
© www.soinside.com 2019 - 2024. All rights reserved.