Creating an XMLDocument

As XML data is created it is written to a stream. By default, an instance of the XMLDocument class maintains an internal stream that will hold the XML data. By allowing the document to store the data in this stream, you may later save the document to the database or write it to another stream. If you have no wish to save the document, you can specify an alternative stream where the XML data should be written as it is created. This can help to reduce memory overhead if the data stream is very large. For example, data for a large report may not need to be stored in the database. This data can be generated and processed on-the-fly without any intermediate storage.

Figure 1. XMLDocument Constructor
XMLDocument(String encoding);
XMLDocument(OutputStream stream, String encoding);

Both constructors take a parameter to set the character encoding. You can set the encoding value using one of the encoding constants or an encoding string of your own choosing.

The first constructor is used when you want the XML document to use its internal string buffer to store the XML data. This allows you to save the document to the database later or to write to another stream once it is complete. If you intend to load an XML document from the database, you should also use this constructor. In that event, the encoding string is irrelevant.

The second constructor allows you to specify an output stream that the document should be written to as it is created. This precludes the possibility of storing the document in the database once it is complete. However, for large documents that do not need to be stored but rather printed, saved to a file, or transferred over a network, this is a more efficient method that the first. For streams such as file and print streams that are required to be explicitly opened, it is important that the stream passed to this constructor is already open as the document will expect to be able to write to it immediately.