0

I've got a CSV file with both the data I want to replace in an XML and the data I want to replace it with; Header A is what I want to replace; Header B is what I want to replace it with:

HeaderA, HeaderB 
Data A1, Data B1
Data A2, Data B2
Data A3, Data B3

I'm trying to do this with power-shell using this solution provided here:

Replace multiple Strings with Data from CSV

Modifying the solution provided there to:

$CSVData = Import-Csv .\MyCSV.csv
$xml = Get-Content -Raw .\MyXML.xml
foreach ($row in $CSVData) {
    $xml.Replace($row.HeaderA, $row.HeaderB) |
      Out-File ".\MyXMLCopy.xml"
}

I only need the XML as one file; as opposed to what was needed there.

EDIT: What about combining this operation with a multiple file replace? As discussed: Replace multiple strings in a file using powershell So far I've been attempting this:

       $ReplaceList = Import-Csv ".MyCSV.csv"
        $ChangeList = Get-Childitem ".\*Map.xml" | ForEach-Object FullName

        foreach ($file in $ChangeList) {
        foreach ($row in $ReplaceList) {
            Get-Content $file |
            ForEach-Object {$_ -replace "$($row.HeaderA)", "$($row.HeaderB)"} 
| Set-Content $_.FullName
        }}

Failing at Set-Content

1 Answer 1

0

It is important to remember that PowerShell strings are immutable. That means that $xml.Replace doesn't change $xml in any way, it returns a new string where the replacement has been done. So, in order to keep all replacements you need to set $xml to the result of each replacement.

What your code does is take each row, do the replacement on the original xml and write the result to the output file. Thus you only get the result of the last replacement.

The following code assigns $xml after each replacement and only outputs the result once.

$CSVData = Import-Csv .\MyCSV.csv
$xml = Get-Content -Raw .\MyXML.xml
foreach ($row in $CSVData) {
    $xml = $xml.Replace($row.HeaderA, $row.HeaderB) 
}
$xml | Out-File ".\MyXMLCopy.xml"
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, this worked perfectly (I'm fairly new to PowerShell.
@Christopher Prince: You're welcome, I just added some more info to make it more beginner-friendly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.