Wednesday, June 16, 2004

Cloning and Inserting an XML Node with C#

I've recently had some trouble locating some code to append data to an XML file. Just in case someone else out there is having the same problem, here is some code to assist.


//Instantiate an XML Document and load the file

XmlDocument objDoc = new XmlDocument();

objDoc.Load(Server.MapPath("/") + "/files/myxmlfile.xml");


//Set a root node pointer

XmlNode objRoot = objDoc.DocumentElement;


//locate the node you want to clone and copy it to a new node

string strXmlQuery = "/myNodePath/myNode";

XmlNode objToBeCloned = objRoot.SelectSingleNode(strXmlQuery);

XmlNode objNewNode = objToBeCloned.CloneNode(true);

//The bool value indicates true to copy the whole tree of chile nodes, false only copies the top node


//Alter the node and child nodes as relevant

objNewNode.InnerText = "alter node text or child node text and/or attributes as needed";


//Insert the node after the last child of a commoon parent (see note below)

objRoot.InsertAfter(objNewNode, objRoot.LastChild);


//Resave the xml file

objFilters.Save(Server.MapPath("/") + "/files/myxmlfile.xml");


NOTE: it is critical that the InsertAfter call is made from the common parent for the nodes. I initially tried using objDoc and it failed with "The referenced node is not a child of this node." One last thing, the SelectSingleNode call uses XPath to locate the node.


Well, I hope this helps someone else. There are some areas that may be improved, but this works and made sense in the scheme of the application I was writing.

1 comment:

angsram said...

This was exactly what I was looking for. I was trying to clone a node and add it to same root but getting some errors. Got a work around of taking a different another copy of xmldocument and appending to it. But this looks like more simple and straight forward way..Thank you very much.