Howler Howler - 2 months ago 15
C# Question

Append XML string block to existing XmlDocument

I have an XmlDocument that already exists and is read from a file.

I would like to add a chunk of Xml to a node in the document. Is there a good way to create and add all the nodes without cluttering my code with many .CreateNote and .AppendChild calls?

I would like some way of making a string or stringBuilder of a valid Xml section and just appending that to an XmlNode.

ex:
Original XmlDoc:

<MyXml>
<Employee>
</Employee>
</MyXml>


and, I would like to add a Demographic (with several children) tag to Employee:

<MyXml>
<Employee>
<Demographic>
<Age/>
<DOB/>
</Demographic>
</Employee>
</MyXml>

Answer

I suggest using XmlDocument.CreateDocumentFragment if you have the data in free form strings. You'll still have to use AppendChild to add the fragment to a node, but you have the freedom of building the XML in your StringBuilder.

XmlDocument xdoc = new XmlDocument();
xdoc.LoadXml(@"<MyXml><Employee></Employee></MyXml>");

XmlDocumentFragment xfrag = xdoc.CreateDocumentFragment();
xfrag.InnerXml = @"<Demographic><Age/><DOB/></Demographic>";

xdoc.DocumentElement.FirstChild.AppendChild(xfrag);