2020-08-08

Updating XML files with PowerShell

Say you have the following file.xml:

<?xml version="1.0" encoding="UTF-8"?>
<data>
  <item name="Item 1" id="0" />
  <item name="Item 2" id="1001" />
  <item name="Item 3" id="0" />
  <item name="Item 4" id="1002" />
  <item name="Item 5" id="1005" />
  <item name="Item 6" id="0" />
</data>

And you want to replace all those "0" id attributes with incremental values.

If you have PowerShell, this can be accomplished pretty easily with the following commands:

$xml = New-Object xml
$xml.Load("$PWD\file.xml")
$i = 2001; foreach ($item in $xml.data.item) { if ($item.id -eq 0) { $item.id = [string]$i; $i++ } }
$xml.Save("$PWD\updated.xml")

Now your output (updated.xml) looks like:

<?xml version="1.0" encoding="UTF-8"?>
<data>
  <item name="Item 1" id="2001" />
  <item name="Item 2" id="1001" />
  <item name="Item 3" id="2002" />
  <item name="Item 4" id="1002" />
  <item name="Item 5" id="1005" />
  <item name="Item 6" id="2003" />
</data>

Easy-peasy...

2 comments:

  1. I would update slightly the script regarding the encoding.

    Specifically, you should use `Get-Content file.xml -Encoding UTF8` to match the xml encoding.

    Or you can also use the XmlDocument read method.

    ````
    $xml = New-Object xml
    $xml.Load("c:\path\to\file.xml")


    ````

    Hth

    ReplyDelete
    Replies
    1. I like the $xml = New-Object / $xml.Load() approach you suggest, as it makes things more balanced since we are using $xml.Save() anyway, so I have edited the script. Thanks for the insightful comment!

      Delete