Bill
Bill

Reputation:

Can I add one XmlDocument within a node of another XmlDocument in C#?

I have two XmlDocuments. Something like:

<document1>
  <inner />
</document1>

and

<document2>
  <stuff/>
</document2>

I want to put document2 inside of the inner node of document1 so that I end up with a single docement containing:

<document1>
  <inner>
    <document2>
      <stuff/>
    </document2>
  </inner>
</document1>

Upvotes: 3

Views: 2713

Answers (3)

David
David

Reputation: 34563

Here's the code...

XmlDocument document1, document2;
// Load the documents...
XmlElement xmlInner = (XmlElement)document1.SelectSingleNode("/document1/inner");
xmlInner.AppendChild(document1.ImportNode(document2.DocumentElement, true));

Upvotes: 9

i_am_jorf
i_am_jorf

Reputation: 54600

No. You can only have on XmlDocument in an XML DOM. What you want to do is get the DocumentElement associated with document2 and append that XmlElement as a child to the XmlElement.

Upvotes: 0

Grzenio
Grzenio

Reputation: 36649

You can, but effectively a copy will be created. You have to use XmlNode node = document1.ImportNode(document2.RootElement), find the node and add node as a child element.

Example on msdn: http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.importnode.aspx

Upvotes: 2

Related Questions