windows - 使用 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")
解决方案
以下代码可以满足您的需求。
- 您不能用于
SetAttribute
创建具有值/InnerText 的新元素。您需要创建一个元素并将其附加到您所在的节点。在您的示例 xml 中,staff
有两个属性,branch
可以Type
使用SetAttribute
方法进行更新。 - 如果 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")
}
}
}
}
推荐阅读
- python - CVXPY 在简单的二次问题中获得无穷大
- sdl - MonoGame 游戏构造函数挂起
- python - 和 datetime64[ns] 列和 float64 列
- php - 如何只执行特定的 PHP 代码块
- javascript - 在 Google Sheet Apps 脚本中缩进漂亮的 JSON
- java - 如何使用 Spring JDBC 控制运行时新事务
- flutter - 无法显示文件?作为图像
- ffmpeg - ffmpeg 为进入管道的视频添加 tee
- reactjs - 类型的嵌套道具的记录类型
- signalr - 为什么 Blazor 使用 post 而不是 WebSockets?