The Xmlwriter Classes

This article has been excerpted from book "A Programmer's Guide to ADO.NET in C#".

As you've seen in the Microsoft .NET and XML section of this article, the XmlWriter class contains methods and properties to write to XML documents, and XmlTextWriter and XmlNodeWriter come from the XmlWriter class (see figure 6-7).

Figure-6.7.gif

Figure 6-7. XmWriter classes

Besides providing a constructor and three properties (WriteState, XmlLang, and XmlSpace), the XmlWriter classes have many writexxx methods to write to XML documents. This section discusses some of these class methods and properties and uses them in examples of the XmlTextWriter and XmlNodeWriter classes. XmlTextWriter creates a write object and writes to the document. The XmlTextWriter constructor can take three types of inputs: a string, a stream, or a TextWriter.

Xml Writer properties

The XmlWriter class contains three properties: WriterState, XmlLang, and XmlSpace. The WriteState property gets the current state of the XmlWriter class. The values could be Attributes, Start, Element, Content, closed, or Prolog. The return value WriteState.Start means the Write method is not yet called. In otnher cases, it represents what is being written. For example, the return value WriteState.Attribute means the Attribute value has written. WriteState.Close represents that the stream has closed by calling Close method.

Writing XML Items

As discussed earlier, an XML document can have any types of items including elements, Comments, attributes, and white spaces. Although it's not possible to describe all the Writexxx methods here. I'll cover some of them.

The WriteStateDocument and WriteEndDocument methods open and close a document for writing, respectively. You must open a document before you start writing to it. The WriteComment method writes comment to a document. It takes only one string type of argument. The WriteString method writes a string to a document. With the help of WriteString, you can use the WriteStartElement and WriteEndElement method pair to write an element to a document. The WriteStartAttribute and WriteEndAttribute pair writes an attribute. WriteNode is another write method, which writes XmlReader to a document as a node of the document. The following example summarizes all these methods and creates a new XML document with some items in it such as elements, attributes, strings, comments, and so on. (See listing 6-13 in the next section.)

In this example, you create a new XML file, c:\xmlWriterText.xml, using XmlTextWriter:


// Create a new file c:\ xmlWriterTest.Xml

XmlTextWriter
writer = new XmlTextWriter("C:\\xmlWriterTest.xml", null);

After that, add comments and elements to the document using Writexxx methods. After that you can read the books.xml xml file using Xml TextReader and add its elements to xmlWriterTest.xml using XmlTextWriter:


       
// Create an XmlText Reader to read books. xml
        XmlTextReader reader = new XmlTextReader("@c:\books.xml");

        while (reader.Read())
        {
            if (reader.NodeType == XmlNodeType.Element)
            {
               
// Add node.xml to xmlWriterTest .xml using WriteNode
                writer.WriteNode(reader, true);
            }
        }


Listing 6-13 shows an example of using XmlWriter to create a new document and write its items. This program creates a new XML document, xml writer Test, in the C:\root directory.

Listing 6-13 XmlWriter example


using
System;
using
System.Xml;

class
XmlReaderSamp
{

    static void Main(string[] args)
    {
       
// Create a new File c:\xmlWriterTest.xml
        XmlTextWriter writer = new XmlTextWriter("C:\\ xmlWriterTest.xml", null);
 
       
// opens the document
        writer.WriteStartDocument();

        
// write comments
        writer.WriteComment("This Program uses XmlTextWriter.");
        writer.WriteComment("Developed by :Mahesh Chand.");
        writer.WriteComment("= = = = = = = = = = = = = = =");

       
// write first element
        writer.WriteStartElement("root");
        writer.WriteStartElement("r", "RECORD", "urn: record");
 
       
// write next element
        writer.WriteStartElement("FirstName", " ");
        writer.WriteString("Mahesh");
        writer.WriteEndElement();

       
// write one more element
        writer.WriteStartElement("LastName", " ");
        writer.WriteString("Chand");
        writer.WriteEndElement();

       
// Create an XmlTextReader to read books.xml
        XmlTextReader reader = new XmlTextReader(@"C:\Documents and Settings\PuranMAC\My Documents\Visual Studio 2008\Projects\ConsoleApplication2\ConsoleApplication2\XMLFile1.xml");

        while (reader.Read())
        {
            if (reader.NodeType == XmlNodeType.Element)
            {
               
// Add node.xml to xmlWriterTest.xml using WriteNode
                writer.WriteNode(reader, true);
            }
        }

       
// Ends the document.
        writer.WriteEndDocument();
        Console.ReadLine();
        writer.Close();
        return;
    }
 }


Note: In Listing 6-13 you write output of the program to a file. If you want to write your output directly on the console, pass Console.Out as the file name when create an XmlTextWriter object. For example: XmlTextWriter writer = new XmlTextWriter (Console.Out);

When you open C: \ xmlWriterTest.Xml in a browser, the output of the program looks like Listing 6-14.

Listing 6-14. Output of XmlWriterSample.cs class


<?
xml version="1.0" ?>
- <!--  This program uses xmlTextWriter. 
-->
- <!--  Developed by: Mahesh chand.
-->
- <!--  = = = = = = =  = = = = = = 
-->
- <root
>
  - <r:RECORD xmlns:r="urn:record"
>

    <
FirstName>Mahesh</FirstName>
    <
LastName>Chand</LastName>
    - <bookstore
>
      - <book genre="autobiography" publicationdate="1981" ISBN="1-861003-11-0"
>

        <
title>the Autobiography of Benjamin Franklin</title>
        - <author
>

          <
First-name>Benjamin</First-name>
          <
last-name>Franklin</last-name>
        </
author>
        <
price>8.99</price>
      </
book>
      -<book genre="novel" publicationdate="1967" ISBN="0-201-63361-2"
>

        <
title>The confidence man</title>
        - <author
>

          <
first-name>Herman</first-name>
          <
last-name>Malville</last-name>
        </
author>
        <
price>11.99</price>
      </
book>
      -<book genre="Philosophy" publicationdate="1991" ISBN="1-861001-56-6"
>

        <
title>The Gorgias</title>
        - <author
>

          <
name>Plato</name>
        </
author>
        <
price>9.99</price>
      </
book>
    </
bookstore>
  </
r:RECORD>
</
root>

The close method

You use the Close method when you're done with the XmlWriter object, which closes the stream.

Conclusion

Hope this article would have helped you in understanding Xmlwriter Classes. See other articles on the website also for further reference.

 

adobook.jpg This essential guide to Microsoft's ADO.NET overviews C#, then leads you toward deeper understanding of ADO.NET.

Up Next
    Ebook Download
    View all
    Learn
    View all