我试图使用PowerShell脚本自动编辑xml文件。该脚本需要使用.csv文件作为数据源。.csv有两列。A有原始值,B有替换值。
由于.xml文件中存在重复项,因此我只想替换特定元素之间的值,在本例中是name元素。
我尝试编写此脚本(请参阅代码),但替换过程不起作用。在运行脚本时,我没有收到错误消息,但当我在执行脚本后打开.xml文件时,没有一个目标值被更改为.csv文件中显示的值。
预期的行为是name元素中包含的任何值都将被更改为.csv文件中列B下列出的值。
# Load the csv file
$csv = Import-Csv -Path "C:\sourcelabels.csv"
# Load the xml file
$xml = [xml](Get-Content -Path "C:\labelfile.xml")
# Loop through each row in the csv file
foreach ($row in $csv) {
# Find the elements in the xml file that match the value in column A
$elements = $xml.SelectNodes("//element[propertyA='$($row.'Column A')']")
# Replace the value in the <name> element with the value in column B
foreach ($element in $elements) {
$element.SelectSingleNode("name").InnerText = $row.'Column B'
}
}
# Save the updated xml file
$xml.Save("C:\labelfile.xml")
1条答案
按热度按时间iaqfqrcu1#
如果您的labelfile.xml看起来像这样:
您的sourcelabels.csv文件看起来像
然后下面应该工作: