Skip to content

April 16, 2013

Replace an XML node with Powershell

by Scott Newman

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;
	$node.ParentNode.AppendChild($newNode);
	$node.ParentNode.RemoveChild($node);
	
}
$xmlDoc.Save('c:\XMLFileReplaced.xml');
Read more from Powershell, XML

Leave a Reply

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

WordPress.com Logo

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

Google+ photo

You are commenting using your Google+ 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

Note: HTML is allowed. Your email address will never be published.

Subscribe to comments

%d bloggers like this: