使用PowerShell将值从.csv文件写入.xml,我的脚本不起作用-批评我的代码

i7uq4tfw  于 2023-04-09  发布在  Shell
关注(0)|答案(1)|浏览(125)

我试图使用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")
iaqfqrcu

iaqfqrcu1#

如果您的labelfile.xml看起来像这样:

<labels>
    <label>
        <element propertyA="changeMe">
            <name>oldValue</name>
        </element>
    </label>
    <label>
        <element propertyA="DoNotChange">
            <name>KeepMyName</name>
        </element>
    <label>
    </label>
        <element propertyA="changeThisOneToo">
            <name>UpdateThisName</name>
        </element>
    </label>
</labels>

您的sourcelabels.csv文件看起来像

"Column A","Column B"
"changeMe","NewValue"
"changeThisOneToo","This Name Has Been Updated"

然后下面应该工作:

# Load the csv file
$csv = Import-Csv -Path "C:\sourcelabels.csv"

# Load the xml file (this way will use the correct encoding of the file)
$xml = [System.Xml.XmlDocument]::new()
$xml.Load("C:\labelfile.xml")
# get a collection of element nodes
$elementNodes = $xml.SelectNodes("//element")

# Loop through each row in the csv file
foreach ($row in $csv) {
    # Find the elements in the xml file whose propertyA attribute match the value in column A
    $elementNodes | Where-Object { $_.propertyA -eq $row.'Column A' } | ForEach-Object {
        $_.Name = $row.'Column B'
    }
}

# Save the updated xml file
$xml.Save("C:\labelfile.xml")

相关问题