arcticlisa
arcticlisa

Reputation: 73

Add XmlDocument as child node to another XmlDocument

I have two XmlDocuments, one being the root and the other one containing the children. I want to combine them and save them into one document. Currently I have this:

XmlDocument root = new XmlDocument();
root.LoadXml("<tables><table></table></tables>");

XmlDocument childItem = new XmlDocument();                  
childItem.LoadXml(string.Format(@"<item>
 <column columnName=""Article_text"">{0}</column>
 <column columnName=""Article_name"">{1}</column>
 </item>", atext, aname));

 root.AppendChild(childItem);

I want my new document's structure to be tables/table/item. However, the code above throws me an error:

The specified node cannot be inserted as the valid child of this node, because the specified node is the wrong type.

Upvotes: 2

Views: 1613

Answers (1)

Hyarus
Hyarus

Reputation: 952

var newNode = root.ImportNode(childItem.FirstChild, true);
root["tables"]["table"].AppendChild(newNode);

First import your item element to the root document. Expecting that item is your root node you can use FirstChild and ImportNode to get it:

 var newNode = root.ImportNode(childItem.FirstChild, true);

And append it to your table element:

root["tables"]["table"].AppendChild(newNode);

Upvotes: 3

Related Questions