简体   繁体   中英

How to copy node with all its children from an XML document to another one?

I have some C# code to open an XML document and to append the XML element to the selected node. However, I need to get copy of a bunch of nodes from one XML document to include them in another XML document.

How can I do this?

my C# code

    XmlDocument Formal_TemplateField = new XmlDocument();
    XmlDocument BuildMyGridView = new XmlDocument();
    Formal_TemplateField.Load(Server.MapPath("~/Formal_TemplateField.xml"));
    BuildMyGridView.Load(Server.MapPath("~/BuildMyGridView.xml"));

    XmlElement controls = (XmlElement)Formal_TemplateField.SelectSingleNode("controls");
    XmlElement Columns = BuildMyGridView.GetElementById("Columns");

    Columns.AppendChild(controls); //<--- error here
    BuildMyGridView.Save(Server.MapPath("~/BuildMyGridView.xml"));

This code gives me an error (System.NullReferenceException: 'Object reference not set to an instance of an object.')!
What is wrong?

I found the solution and the code will be just like this.

C#

XmlDocument Formal_TemplateField = new XmlDocument();
XmlDocument BuildMyGridView = new XmlDocument();

Formal_TemplateField.Load(Server.MapPath("~/Formal_TemplateField.xml"));
BuildMyGridView.Load(Server.MapPath("~/BuildMyGridView.xml"));

XmlNode NEW_NOOD = BuildMyGridView.ImportNode(Formal_TemplateField.DocumentElement["controls"], true);
BuildMyGridView.DocumentElement.GetElementsByTagName("Columns")[0].AppendChild(NEW_NOOD);

BuildMyGridView.Save(Server.MapPath("~/BuildMyGridView.xml"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM