A Simple Way to Write XML in .NET (XmlTextWriter)


Desktop-as-a-Service Designed for Any Cloud ? Nutanix Frame

Environment: .NET (C#)

XML is a hot topic. A primary reason for it being of interest is the fact that it is simple to understand and simple to use. Any programmer should be able to easily look at an XML file and understand its contents.

.NET contains a number of classes that support XML. Many of these classes make working with XML as easy as understanding XML. I'm going to show you an example of one such class here. This is the XmlTextWriter class.

The XmlTextWriter class allows you to write XML to a file. This class contains a number of methods and properties that will do a lot of the work for you. To use this class, you create a new XmlTextWriter object. You then add the pieces of XML to the object. There are methods for adding each type of element within the XML file. Following are several of these methods:

WriteStartDocumentWrites the XML declaration with the version "1.0".
WriteEndDocumentCloses any open elements or attributes.
CloseCloses the stream.
WriteDocTypeWrites the DOCTYPE declaration with the specified name and optional attributes.
WriteStartElementWrites the specified start tag.
WriteEndElementCloses one element.
WriteFullEndElementCloses one element.
WriteElementStringWrites an element containing a string value.
WriteStartAttributeWrites the start of an attribute.
WriteEndAttributeCloses the previous WriteStartAttribute call.
WriteRawWrites raw markup directly from a string.
WriteStringWrites a string.
WriteAttributesWrites an attribute with the specified value.
WriteCDataWrites out a <![CDATA[...]]> block containing the specified text.
WriteCommentWrites out a comment <!--...--> containing the specified text.
WriteWhitespaceWrites white space.
WriteProcessingInstructionWrites out a processing Instruction with a space between the name and text as follows: <?name text?>.

If you are familiar with XML, then the above methods should make sense. You will create a document, add elements, and then close the document. Within elements you can add sub-elements, attributes, and more. The following listing creates a new XML file called titles.

using System;
using System.IO;
using System.Xml;

public class Sample
  public static void Main()
     XmlTextWriter writer = new XmlTextWriter("titles.xml", null);

     //Write the root element

     //Write sub-elements
     writer.WriteElementString("title", "Unreal Tournament 2003");
     writer.WriteElementString("title", "C&C: Renegade");
     writer.WriteElementString("title", "Dr. Seuss's ABC");

     // end the root element
     //Write the XML to file and close the writer

If you compile and execute this listing, you will create an XML file called titles.xml. This XML file will contain the following:

<items><title>Unreal Tournament 2003</title><title>
C&amp;C: Renegade</title><title>Dr. Seuss's ABC

The listing created an XmlTextWriter object called writer. When it created this object, it associated it to a file called titles.xml. The program then started a root element called items. The call to WriteStartElement created the opening tag for items. This was then followed by three calls to WriteElementString. As you can see, this method creates an element tag using the first parameter (title in this case). The value of the element is the second parameter. Once you are done adding the elements, you need to close the root element. Calling WriteEndElement will close the element that was most recently opened. In this case, that is the root element. With all the data written and the root element closed, you are done sending information to your XmlTextWriter. This means you can close it by calling the Close method.

This listing is relatively simple. The following listing includes a lot more functionality by using more of the XmlTextWriter methods.

using System;
using System.IO;
using System.Xml;

public class Sample
  public static void Main()
     XmlTextWriter writer = new XmlTextWriter("myMedia.xml", null);

     //Use automatic indentation for readability.
     writer.Formatting = Formatting.Indented;

     //Write the root element

     //Start an element

     //Add an attribute to the previously created element 
     writer.WriteAttributeString("rating", "R");

     //add sub-elements
     writer.WriteElementString("title", "The Matrix");
     writer.WriteElementString("format", "DVD");

     //End the item element
     writer.WriteEndElement();  // end item

     //Write some white space between nodes

     //Write a second element using raw string data
     writer.WriteRaw("<item>" + 
                     "<title>BloodWake</title>" +
                     "<format>XBox</format>" + 

     //Write a third element with formatting in the string
     writer.WriteRaw("\n  <item>\n" +
                     "    <title>Unreal Tournament 2003</title>\n" +
                     "    <format>CD</format>\n" + 
                     "  </item>\n");

     // end the root element

     //Write the XML to file and close the writer

The output for this listing is stored in a file called myMedia.xml:

  <item rating="R">
    <title>The Matrix</title>
    <title>Unreal Tournament 2003</title>

The comments within the listing tell you what is happening. One thing to remember is that methods that start something, need to be followed at some point by methods that end what was started. For example, if you call StartElement, you will need to call EndElement. You can start a sub-element within another element. Whenever you call an EndElement method, it will always associate with the last StartElement method that was called. (This works like a stack, not like a queue).

Working with the XmlTextWriter is easy. I suggest you play around with the code and the various methods. You'll quickly find that this code is easy to integrate into your applications. You should also remember that the XmlTextWriter is only one of many XML classes available in .NET. Like the XmlTextWriter, many of the other classes are also easy to use.

About the Author

Bradley Jones

Bradley Jones, in addition to managing CodeGuru, Brad! oversees the Developer.com Newtwork of sites including Codeguru, Developer.com, DevX, VBForums, and over a dozen more with a focus on software development and database technologies. His experience includes development in C, C++, VB, some Java, C#, ASP, COBOL, and more as well as having been a developer, consultant, analyst, lead, and much more. His recent books include Teach Yourself the C# Language in 21 Days, Web 2.0 Heroes, and Windows Live Essentials and Services.
Google+ Profile | Linked-In Profile | Facebook Page


  • Mr

    Posted by Johann Smit on 05/29/2014 09:43am

    Excellent. This is really a great help.

  • Schema Dataset to Xml

    Posted by siva_dq on 08/03/2007 05:35pm

    Hello Bradley,
    I have a problem while generating a xml document from a respective schema loaded into a dataset,to explain more plz have a look at the following code:
    XmlDataDocument xdd = new XmlDataDocument();
    xdd.DataSet.ReadXmlSchema("C:\\schema_test.xsd");//loading the schema into the dataset
    xdd.DataSet.WriteXml("C:\\xml_file.xml"); //writing the generated xml document into the xml_file.xml file
    I have a problem with the xml file I thought it will work is there something that i have missed (or)
    can u please suggest me some approach with which i can create an xml document from respective schema
    programatically(with out tool) ,please provide me with some sample codes or links to go through .Waiting for the reply thank you.

  • Displaying an xml file in a windows GUI?

    Posted by Legacy on 10/23/2002 07:00am

    Originally posted by: Mikael

    Is there any component i C# that can display and format an XML file?

  • You must have javascript enabled in order to post comments.

Leave a Comment
  • Your email address will not be published. All fields are required.

Most Popular Programming Stories

More for Developers

RSS Feeds

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