Home > Articles > Web Services > XML

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

The XmlTextWriter Class

The XmlTextWriter class provides the ability to write properly formed XML to a file or other stream. The XML created conforms to the W3C XML specification version 1.0, and also to the Namespaces in XML specification. Using this class is straightforward:

  1. Create an instance of the class, passing the name of the file to be used for output and the type of encoding to use. Pass a null reference for the encoding argument to use UTF-8 encoding.

  2. Set object properties as needed to control the formatting of the output.

  3. Call object methods to write elements and attributes to the file.

  4. Close the file.

The properties and methods of the XmlTextWriter class that you will use most often are described in Table 13.5 and Table 13.6.

Table 13.5 Commonly Needed Properties of the XmlTextWriter Class

Property

Description

Formatting

Specifies the formatting of the output. Possible settings are Formatting.Indented to indent child elements with respect to their parents. Set to Formatting.None for no indentation (the default).

Indentation

Specifies how many characters to indent by for each level in the element hierarchy when Formatting is set to indented. The default is 2.

IndentChar

Specifies the character to use for indenting when Formatting is set to indented. The default is the space character. Must be a valid white space character.

Namespaces

Set to True to enable namespace support, and set to False for no namespace support. The default is True.

QuoteChar

Specifies the character to use for quoting attribute values. Must be either the double quote (") or the single quote ($). The default is the double quote.


Table 13.6 Commonly Needed Methods of the XmlTextWriter Class

Method

Description

Close()

Closes the output stream or file.

Flush()

Flushes the writer buffer to the output file or stream.

WriteAttributeString
(localName, value)

WriteAttributeString
(localName, ns, value)

WriteAttributeString
(prefix, localName, ns, value)

Writes an attribute with the specified local name and value. Use the other forms of the method to include as namespace URI and a prefix.

WriteCData(text)

Writes a CDATA section containing text.

WriteComment(text)

Writes an XML comment containing text.

WriteDocType
(name,
pubid, sysid, subset)

Writes a DOCTYPE element. Name is a required argument specifying the name of the DOCTYPE. The other arguments are optional and are for writing PUBLIC "pubid," SYSTEM "sysid," and [subset] to the DOCTYPE element.

WriteElementString
(localName, value)

WriteElementString
(localName, ns, value)

Writes an element with the specified local name and value. Use the second form of the method to include a namespace URI.

WriteEndAttribute()

Completes an attribute started with WriteStartAttribute().

WriteEndDocument()

Closes any open elements or attributes.

WriteEndElement()

Writes the closing tag for an element started with WriteStartElement(). If the element is empty it will be closed with a short end tag: <element />.

WriteFullEndElement()

Writes the closing tag for an element started with WriteStartElement(). If the element is empty it will be closed with a separate end tag: <element></element>.

WriteProcessingInstruction
(name, text)

Writes a processing instruction with the specified name and text.

WriteRaw(text)

Writes raw text to the output.

WriteStartAttribute
(localName, ns)

WriteStartAttribute
(prefix, localName, ns)

Writes the start of an attribute with the specified local name and namespace URI. Use the second form of the method to add a prefix to the local name.

WriteStartDocument()

WriteStartDocument
(standalone)

Writes the XML declaration with the version "1.0." Use the second form of the method to include "standalone=yes" or "standalone=no" in the declaration.

WriteStartElement(localName)

WriteStartElement
(localName, ns)

WriteStartElement
(prefix, localName, ns)

Writes a start element with the specified local name. Use the other forms of the method to include a namespace URI and a prefix in the element.

WriteWhitespace(string)

Writes white space to the output. If string contains non–white space characters, an exception ocurs.


The program in Listing 13.3 demonstrates how to use the XmlTextWriter class. This is a C# console application that creates a new XML file named XmlOutput.xml. Some data is written to the file, and then it is closed. Finally, the file is read back using the XmlTextReader class and then written to the console. Reading the file with XmlTextReader is often a good idea to verify that the file is well-formed. The results of running the program are shown in Figure 13.2.

Figure 13.2 Running the C# console application in Listing 13.3

Listing 13.3 Console Application Demonstrating the XmlTextWriter Class

using System;
using System.IO;
using System.Xml;
class XmlWriter
{
  private const string m_FileName = "XmlOutput.xml";
  static void Main()
  {
    XmlTextWriter w = null;
    XmlTextReader rdr = null;
    try
    {
    w = new XmlTextWriter(m_FileName, null);
    w.Formatting = Formatting.Indented;
    w.Indentation = 4;
    //Start the document.
    w.WriteStartDocument();
    //Write the root element.
    w.WriteStartElement( "contacts" );
    // Start a "person" element.
    w.WriteStartElement( "person" );
    //Write a "category" attribute.
    w.WriteAttributeString("category", "personal");
    //Write a "name" element.
    w.WriteElementString("name", "John Adams");
    //Write a "phone" element.
    w.WriteElementString("phone", "555-555-1212");
    //Write an "email" element.
      w.WriteElementString("email", "john.adams@nowhere.net");
    //Close the "person" element.
    w.WriteEndElement();
    //Write another "person" element.
      w.WriteStartElement( "person" );
      w.WriteAttributeString("category", "business");
      w.WriteElementString("name", "Mandy Pearson");
      w.WriteElementString("phone", "555-444-3232");
      w.WriteElementString("email", "mandyp@overthere.org");
      w.WriteEndElement();
    // Close the root element.
    w.WriteEndElement();
    //Flush and close.
    w.Flush();
    w.Close();
    //Read the file back in and display it.
    rdr = new XmlTextReader( m_FileName );
    XmlDocument xmlDoc = new XmlDocument();
    // Preserve white space for readability
    xmlDoc.PreserveWhitespace = true;
    xmlDoc.Load( rdr );
    // Write the content to the console
    Console.Write( xmlDoc.InnerXml );
    }
    catch (Exception e)
    {
    Console.WriteLine( "Exception: ", e.ToString() );
    }
    finally
    {
    Console.WriteLine();
    Console.WriteLine( "Processing completed." );
    if ( rdr != null )
      rdr.Close();
    if ( w != null )
      w.Close();
    }
  }
}
  • + Share This
  • 🔖 Save To Your Account