Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add new root element to a C# XmlDocument?

I have, outside of my control, an XmlDocument which has a structure like the following:

<parent1>
...minor amount of data...
</parent1>

I have another XmlDocument, also outside of my control, which has the following structure:

<parent2>
..very large amount of data...
</parent2>

I need an XmlDocument in the format:

<parent1>
...minor amount of data...
<parent2>
..very large amount of data...
</parent2>
</parent1>

I don't want to make a copy of parent2. How can I get the structure I need, without copying parent2? I believe this means

oParent1.DocumentElement.AppendChild(oParent1.ImportNode(oParent2.DocumentElement, true));

is out of the question.

Any good solutions out there?

like image 362
aepheus Avatar asked Feb 15 '10 21:02

aepheus


People also ask

How To add root node in Xml using c#?

Here you go: string xmlFile = @"C:\yourFile. xml"; XElement doc = XElement. Load(xmlFile); XElement root = new XElement("MAIN", doc); root.

What is the root element of an html element?

The <html> HTML element represents the root (top-level element) of an HTML document, so it is also referred to as the root element. All other elements must be descendants of this element. None. One <head> element, followed by one <body> element.


1 Answers

Just remove the DocumentElement from the parent2 XmlDocument, then append the imported parent1 node to the XmlDocument (directly -- NOT to the DocumentElement) and re-append the removed parent2 node to the imported parent1 node:

var p1node = oParent2.ImportNode(oParent1.DocumentElement, true);
var p2node = oParent2.RemoveChild(oParent2.DocumentElement);

oParent2.AppendChild(p1node);
p1node.AppendChild(p2node);
like image 189
itowlson Avatar answered Oct 14 '22 04:10

itowlson