Create an XML File or XmlDocument Directly from a StringBuilder

Create an XML File or XmlDocument Directly from a StringBuilder

An earlier DevX tip, “Create a New XML File Using XmlDocument,” showed how to create a new XmlDocument, populate it, and save the results to a file. This tip uses the same XML example, but builds the document with a StringBuilder instead, which is simpler than working directly with the System.Xml.XmlDocument class.

Suppose you want to build this XML:

      XML    This is a list of my XML articles.    true  

The following method shows how to build the preceding document with a StringBuilder. The following code gets a StringBuilder containing the minimal XML, appends strings containing the elements, loads an XmlDocument instance from the StringBuilder contents, and returns the populated XmlDocument object:

public XmlDocument BuildXmlDocument(){   StringBuilder Document = CreateBaseStringBuilder(); // create a generic XML string   //declare the root.   Document.AppendLine("");   // declare child node.   Document.AppendLine(""); //We could tab indention   // add child node's child node   Document.AppendLine("XML");   // add another child node   Document.AppendLine("This is a list of my XML articles.");   // and another   Document.AppendLine("true");   // close the Category node.   Document.AppendLine("");   // close the root node   Document.AppendLine("");   // now read the contents into an XmlDocument   try   {      // Create the new Instance.      XmlDocument XMLDocument = new XmlDocument();      // Add the content      XMLDocument.LoadXml(Document.ToString());      // return it.      return (XMLDocument);   }   catch(Exception ex)   {      // in case of failure return null      return (null);   }}// This function creates a new instance of System.Text.StringBuilder, // adds a Basic XmlDocumentDeclaration, // and returns the new StringBuilder.private StringBuilder CreateBaseStringBuilder(){   StringBuilder BaseDocument = new StringBuilder();   BaseDocument.AppendLine("");   return (BaseDocument);}

Note that you’d need to call the returned XmlDocument’s Save method from the calling function.

See also  How to Create and Deploy QR Codes Online: A Comprehensive Guide

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist