Quantcast
Channel: Rename Root Node in XML
Viewing all articles
Browse latest Browse all 6

Rename Root Node in XML

$
0
0

Hey Jason,

thanks for providing that example. When testing I spotted that this does not currently copy over the attributes, so I've added in some code to do that. I've also got it to keep the prefix and namespace of the original when renaming by adding those values to the doc.CreateElement method - but I suspect in a number of cases that won't be wanted so anyone following this thread may want to just pass in the new root node name here.

publicvoid RenameRootNode(XmlDocument doc, string rootNode)

{

 //copy the prefix & namespace too

 XmlElement elem = doc.CreateElement(doc.DocumentElement.Prefix, rootNode,doc.DocumentElement.NamespaceURI);

 //XmlElement elem = doc.CreateElement(rootNode);//copy the attributeswhile (doc.DocumentElement.HasAttributes)

 {

  elem.Attributes.Append(doc.DocumentElement.Attributes[0]);

 }

 //copy the 1st level child elementswhile (doc.DocumentElement.HasChildNodes)

 {

  elem.AppendChild(doc.DocumentElement.ChildNodes[0]); 

 }

 //replace the document element with our new one.

 doc.RemoveChild(doc.DocumentElement);

 doc.AppendChild(elem);

}

Cheers,

JB


Viewing all articles
Browse latest Browse all 6

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>