Replace an XML node with Powershell

There may be a better way to do this (the xml spec defines a renameNode method, but as far as I can tell MS hasn’t implemented this, and if they have I couldn’t find it), but this sufficed for my purposes.  This just creates a new node under the parent of the node you’re looking for and then copies the original nodes’ text content into the new node.  It then removes the original node. 

[xml]$xmlDoc = Get-Content c:\XMLFile.xml

foreach($node in $xmlDoc.SelectNodes('/Node1/Node2')){
	$newNode = $xmlDoc.CreateNode([System.Xml.XmlNodeType]::Element, $node.Prefix, 'NewNode', $node.NamespaceURI);
	$newNode.InnerText = $node.InnerText;

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.