Search/Replace XML via Powershell

rygerx

I am looking for a way to have a powershell search through an XML doc searching for a specific ID that's within an "ID" tag, then locate the very next tag and replace it's value with "true". The IDs would be provided by the first column of a csv file. Here is an example of the XML structure:

<primary>
<main>
<id>47</id>
<desc>foobar</desc>
<indicatorflag>false</indicatorflag>
</main>
</primary>
<primary>
<main>
<id>48</id>
<desc>foobar</desc>
<indicatorflag>false</indicatorflag>
</main>
</primary>
<primary>
<main>
<id>49</id>
<desc>foobar</desc>
<indicatorflag>false</indicatorflag>
</main>
</primary>
<primary>
<main>
<id>50</id>
<desc>foobar</desc>
<indicatorflag>false</indicatorflag>
</main>
</primary>
<primary>
<main>
<id>51</id>
<desc>foobar</desc>
<indicatorflag>false</indicatorflag>
</main>
</primary>

Now imagine the csv file has, in column 1:

47
49

I would like only those indicator flag tags to be updated to true.
Any help would be very appreciated!!

Theo

First thing: Don't use regex replace on xml. PowerShell is very able to handle (valid) XML.

As commented, the XMLyou show is invalid as it is missing a root element.
After fixing the XML by encompassing it all inside a <root>...</root> element, you can read this in like this:

[xml]$xml = Get-Content -Path 'D:\Test\input.xml' -Raw

Next, read the file to get the id's to update. If this file is like you show us, a text file where each id is on its own new line, use this:

$ids = Get-Content -Path 'D:\Test\ids.txt'

If however, this file IS a CSV file, something like

"ID","Something"
"47","Whatever"
"49","Anything"

then read the ids as array from it using:

$ids = (Import-Csv -Path  'D:\Test\ids.csv').ID

You can now loop over the id's and change the value of the belonging <indicatorflag> tag:

foreach ($id in $ids) {
    ($xml.root.primary.main | Where-Object {$_.id -eq $id}).indicatorflag = 'true'
}

# save the updated XML
$xml.Save('D:\Test\output.xml')

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related