Tuesday, January 19, 2010

Adding a Child node to an XML file using PowerShell

There has been a need to add a child node to an XML file. Doing that using powershell can be seen here
------
[xml]$Config = Get-Content "C:\tofolder\Files\myfolder\config.xml"
$element = $Config.CreateElement("MyKeyElement")
$element.setattribute("Value", "xxxyyyzzz")
$Config.get_firstChild().appendchild($element)
$Config.Save("C:\tofolder\Files\myfolder\config.xml")

---------
Thus, saving the config file appends the changes in the config file. Once you open the config.xml after running the above script you can see "MyKeyElement" element has been updated with its value in the config.xml file.


Hope this helps someone.

2 comments: