首页 > 解决方案 > 使用 Powershell 更新基于 CSV 值的 XML

问题描述

我有一个 CSV 文件,其值如下:

Age , Status

29 ,    0
41 ,    1
44,     1
27,     0
60,     1

XML如下:

<office>
  <staff branch="Torrance" Type="Implementation">
    <employee>
        <Name>Raj Parpani</Name>
        <function>Implementation</function>
        <age>29</age>
    </employee>
    <employee>
        <Name>Kevin Woo</Name>
        <function>Consultant</function>
        <age>41</age>
    </employee>
  </staff>
  <staff branch="Irvine" Type="Operations">
   <employee>
    <Name>David Woo</Name>
    <function>Data</function>
    <age>42</age>
   </employee>
   </staff>
 </office>

如果 XML 年龄等于 CSV 中的年龄,我必须将该年龄的状态属性从 csv 附加到员工。我已经尝试了如下代码:

原始代码

$csv = Import-Csv 'C:\Users\rparpani\Desktop\test2.csv' | Select-Object "Age","Status"
$xml = New-Object XML
$xml.Load("C:\Users\rparpani\Desktop\test.xml")

$nodes = $xml.SelectNodes("/office/staff/employee")

Foreach($row in $csv)
{
    foreach($node in $nodes)
    {

    if($node.age -eq  $row.age)
    {
    $node.SetAttribute("status", $row.Status);
    }


    }

}

有人可以建议如何改变它来做我想做的事


修改后的代码

    $csv = Import-Csv 'C:\Users\rparpani\Desktop\test2.csv' | Select-Object "Age","Status"
    $xml = New-Object XML
    $xml.Load("C:\Users\rparpani\Desktop\test.xml")

    $nodes = $xml.SelectNodes("/office/staff/employee")


    foreach($row in $csv) {
      foreach($node in $nodes) {
        if ($node.age -eq $row.age) {
          if ($node.status) {
            $node.status.innerText = $row.Status
          }
          else {
            $status = $xml.CreateNode("element", "status", "")
            $status.InnerText = $row.status
            $node.AppendChild($status)
          }
        }
      }
    }

    $xml.Save("C:\Users\rparpani\Desktop\test.xml")

标签: windowspowershellloopsfor-loopforeach

解决方案


以下代码可以满足您的需求。

  1. 您不能用于SetAttribute创建具有值/InnerText 的新元素。您需要创建一个元素并将其附加到您所在的节点。在您的示例 xml 中,staff有两个属性,branch可以Type使用SetAttribute方法进行更新。
  2. 如果 Status 已经存在,用新值更新它。否则创建一个新元素。

CSV 内容

Age,Status
29,0
41,1
44,1
27,0
60,1

将属性添加到节点`Employee的脚本

foreach($row in $csv) {
  foreach($node in $nodes) {
    if ($node.age -eq $row.age) {
      if ($row.status -eq "0") {
        $node.SetAttribute("status", "Hired")
      }
      else {
        $node.SetAttribute("status", "Fired")
      }
    }
  }
}


推荐阅读