簡體   English   中英

如何使用 PowerShell 更改 XML 元素屬性的值?

[英]How to change the value of XML Element attribute using PowerShell?

我正在嘗試從 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 中使用一個值(例如 New York)更改它,並使用以下代碼來執行此操作

       $xml=New-Object XML

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

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

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

但是得到一個錯誤,指出找不到元素。

有人可以幫忙嗎?

請嘗試以下操作:

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

這將遍歷 SelectNodes() 返回的所有節點並修改每個節點。

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

如果我們從控制台獲取屬性並更改其值?

$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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM