10.3. Techniques for Writing XML Data

 < Day Day Up > 

In many cases, the easiest way to present data in an XML format is to use .NET serialization. As demonstrated in Section 10.1, if the data is in a collection class, it can be serialized using the XmlSerializer class; as we see in the next chapter, if it's in a DataSet, the DataSet.WriteXml method can be applied. The advantages of serialization are that it is easy to use, generates well-formed XML, and is symmetrical the XML that is written can be read back to create the original data objects.

For cases where serialization is not an option a comma delimited file, for instance or where more control over the XML layout is needed, the XmlWriter class is the best .NET solution.

Writing XML with the XmlWriter Class

The XmlWriter class offers precise control over each character written to an XML stream or file. However, this flexibility does require a general knowledge of XML and can be tedious to code, because a distinct Writexxx method is used to generate each node type. On the positive side, it offers several compliance checking features, and the ability to write CLR typed data directly to the XML stream:

  • XmlWriterSettings. CheckCharacters property configures the XmlWriter to check for illegal characters in text nodes and XML names, as well as check the validity of XML names. An exception is thrown if an invalid character is detected.

  • XmlWriterSettings. ConformanceLevel property configures the XmlWriter to guarantee that the stream complies with the conformance level that is specified. For example, the XML may be set to conform to a document or document fragment.

  • XmlWriter. WriteValue method is used to write data to the XML stream as a CLR type (int, double, and so on) without having to first convert it to a string.

Listing 10-9 illustrates the basic principles involved in using the XmlWriter class. Not surprisingly, there are a lot of similarities to the closely related XmlReader class. Both use the Create method to create an object instance, and both have constructor overloads that accept a settings object XmlWriterSettings, in this case to define the behavior of the reader or writer. The most important of these setting properties is the conformance level that specifies either document or fragment (a subtree) conformance.

A series of self-describing methods, which support all the node types listed in Table 10-1, generate the XML. Note that exception handling should always be enabled to trap any attempt to write an invalid name or character.

Listing 10-9. Write XML Using XmlWriter Class
 private void WriteMovie() {    string[,] movieList = { { "Annie Hall", "Woody Allen" },                        { "Lawrence of Arabia", "David Lean" } };    // (1) Define settings to govern writer actions    XmlWriterSettings settings = new XmlWriterSettings();    settings.Indent = true;    settings.IndentChars = ("    ");    settings.ConformanceLevel = ConformanceLevel.Document;    settings.CloseOutput = false;    settings.OmitXmlDeclaration = false;    // (2) Create XmlWriter object    XmlWriter writer = XmlWriter.Create("c:\\mymovies.xml",                                         settings);    writer.WriteStartDocument();    writer.WriteComment("Output from xmlwriter class");    writer.WriteStartElement("films");    for (int i = 0; i <= movieList.GetUpperBound(0) ; i++)    {       try       {          writer.WriteStartElement("movie");          writer.WriteElementString("Title", movieList[i, 0]);          writer.WriteElementString("Director", movieList[i, 1]);          writer.WriteStartElement("Movie_ID");          writer.WriteValue(i); // No need to convert to string          writer.WriteEndElement();          writer.WriteEndElement();       }       catch (Exception ex)       {          MessageBox.Show(ex.Message);       }    }    writer.WriteEndElement();    writer.Flush();  // Flush any remaining content to XML stream    writer.Close();    /*       Output:       <?xml version="1.0" encoding="utf-8"?>       <!--Output from xmlwriter class-->       <films>          <movie>             <Title>Annie Hall</Title>             <Director>Woody Allen</Director>             <Movie_ID>0</Movie_ID>          </movie>          <movie>             <Title>Lawrence of Arabia</Title>             <Director>David Lean</Director>             <Movie_ID>1</Movie_ID>          </movie>       </films>    */  } 

Before leaving the topic of XML writing, note that .NET also provides XmlTextWriter and XmlNodeWriter classes as concrete implementations of the abstract XmlWriter class. The former does not offer any significant advantages over the XmlWriter. The node writer is a bit more useful. It creates a DOM tree in memory that can be processed using the many classes and methods designed for that task. Refer to .NET documentation for XmlNodeWriter details.

     < Day Day Up > 

    Core C# and  .NET
    Core C# and .NET
    ISBN: 131472275
    EAN: N/A
    Year: 2005
    Pages: 219

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net