update XML from the command line [windows]

I have a few applications which store their config files in XML format. For a regular application, using a text based config, I could update a value easily enough by using perl, or sed, or awk, or any one of a million tools. I'm looking for something similar for XML, which will allow me to easily and reliably perform operations like: update a value, add a node, or remove one.

Regular text parsing would seem to be too risky, as I have no real guarantees about the physical file format.


XML parsing in MS Powershell is easier than any parsing mechanism I've seen in any other language or environment I've personally encountered.

Given some XML file (test.xml):

<root>
  <one>I like applesauce</one>
  <two>You sure bet I do!</two>
</root>

You can easily access, modify and append nodes, values and attributes of the XML file from inside Powershell.

# load XML file into local variable and cast as XML type.
$doc = [xml](Get-Content ./test.xml)

$doc.root.one                                   #echoes "I like applesauce"
$doc.root.one = "Who doesn't like applesauce?"  #replace inner text of <one> node

# create new node...
$newNode = $doc.CreateElement("three")
$newNode.set_InnerText("And don't you forget it!")

# ...and position it in the hierarchy
$doc.root.AppendChild($newNode)

# write results to disk
$doc.save("./testNew.xml")

Resulting XML in file testNew.xml:

<root>
  <one>Who doesn't like applesauce?</one>
  <two>You sure bet I do!</two>
  <three>And don't you forget it!</three>
</root>

Incredibly easy! Enjoy.

Powershell is Microsoft's new shell that ships with Windows Server 2008 and Windows 7 and is a free download for XP/Vista/Server 2003 (perhaps others).

Some useful links:
Generating XML from other sources
Adding elements to XML:
Sample 1, MSDN PowerShell blog
Sample 2, PC-Pro(UK)