C#: Use Of XmlDocumentFragment
To create even a simple hierarchy of XmlNodes, we need several successive calls of the CreateElement and AppendChild methods, and I don’t even mention about adding of attributes. But there is an easier way to achieve that. XmlDocumentFragment is a lightweight object, that is useful for inserting a small Xml-fragment into a document. Below is the method creating a new XmlNode-object based on the passed xml-based string:
public static XmlNode CreateNode(XmlDocument xmlDoc, string nodesXml)
{
XmlDocumentFragment xmlDocFragment = xmlDoc.CreateDocumentFragment();
xmlDocFragment.InnerXml = nodesXml;
return xmlDocFragment;
}
The XmlDocumentFragment is derived from XmlNode and supports all node manipulations (insert/remove/replace) and capabilities. The CreateNode method can be used in the following way:
// create XmlDocument object
XmlDocument xmlDOc = new XmlDocument();
xmlDOc.LoadXml(@"<rootNode><firstChildNode name=""first"" /></rootNode>");
XmlNode rootNode = xmlDOc.SelectSingleNode("/rootNode");
rootNode.AppendChild(CreateNode(xmlDOc,
@"<secondChildNode name=""secondChildNode""><thirdChildNode name=""thirdChildNode"" /></secondChildNode>"));