Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: .NET
Expertise: Beginner
Apr 4, 2009

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 version="1.0" encoding="utf-8"?>
  <Category ID="01">
    <Description>This is a list of my XML articles.</Description>

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.

   // declare child node.
   Document.AppendLine("<Category ID=\"01\">"); //We could tab indention

   // add child node's child node

   // add another child node
   Document.AppendLine("<Description>This is a list of my XML articles.</Description>");

   // and another

   // close the Category node.

   // close the root node

   // now read the contents into an XmlDocument
      // Create the new Instance.
      XmlDocument XMLDocument = new XmlDocument();

      // Add the content

      // 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("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
   return (BaseDocument);

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

Julio Henriquez
Thanks for your registration, follow us on our social networks to keep up-to-date