Home > C#, XML > C#: Use Of XmlDocumentFragment

C#: Use Of XmlDocumentFragment

January 18th, 2012 Leave a comment Go to comments

    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>"));
 
Categories: C#, XML Tags: ,
  1. No comments yet.
  1. No trackbacks yet.