Howler Howler - 1 year ago 67
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.

Original XmlDoc:


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


Answer Source

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();

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