Writing an XML Declaration

Once the XmlTextWriter is created and initialized and the properties have been set to your liking, you can start writing XML data to the stream. The XmlTextWriter provides a rich API for writing nodes to the XML data stream. This section will look at the methods for writing the most important nodes: XML Declarations, Elements, and Attributes.

An XML declaration is not required in an XML document, but it can provide helpful information for parsers. The XmlTextWriter provides WriteStartDocument for writing the XML declaration to the XML stream. The API allows you to specify whether the document will be a standalone. Since DocumentType nodes are not supported by the .NET Compact Framework's XmlTextWriter, the document should always stand alone, but setting the standalone value to false will not raise an exception.

The WriteStartDocument must be the first write method executed after the constructor if you want to include an XML declaration. If this method is called after any other write method, an InvalidOperationException will be raised. If you choose not to write an XML declaration node, the writer will assume that you are writing an XML fragment node. This means that well-formedness rules that apply to the root node will not be checked. For example, you will be able to write more than one root node without raising an exception.

Listing 10.22 shows how to write a XML declaration to an XML stream. It also demonstrates calling WriteEndDocument to signal the end of the XML document to the writer.

Listing 10.22.
C#
XmlTextWriter writer =
  new XmlTextWriter("startdoc.xml", Encoding.UTF8);
writer.Formatting = Formatting.Indented;

writer.WriteStartDocument(true);
writer.WriteElementString("root", null);
writer.WriteEndDocument();
writer.Close();

VB
Dim writer As
  New XmlTextWriter("startdoc.xml", Encoding.UTF8)
writer.Formatting = Formatting.Indented

writer.WriteStartDocument(true)
writer.WriteElementString("root", null)
writer.WriteEndDocument()
writer.Close()

Output
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<root />

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.210.205