Writing an XML Document Using XmlLite

This topic illustrates how to implement an XmlLite writer application. It then provides a simple example that writes an XML file. Also included is the console output from the example.

This example includes the following files:

To create the example

  1. Create a Visual Studio 2005 project. For details of how to do this, see Building XmlLite Applications.

  2. Copy the C++ source code for this example and paste it into your C++ source file.

  3. Build the example.

  4. Run the sample and verify that the output matches the output provided.

The following is a detailed list of what you need to do to implement an XmlLite writer application:

  • As with the reader example, create an instance of a class that extends the IStream interface. For the writer, if you are creating your own class that extends IStream, it is not necessary to implement the Seek and Stat methods.

  • As with the reader example, use the CComPtr class when declaring the variables that will contain the file writer variable.

  • Declare and instantiate an instance of IXmlWriter. Also use CComPtr when declaring the IXmlWriter variable. This is the declaration of IXmlWriter from the example:

    CComPtr<IXmlWriter> pWriter;
  • Use the SetOutput method to set the output stream of the IXmlWriter. Set this to an instance of your class that extends the IStream interface.

  • Set appropriate options on the writer. For example, you might want to configure the writer so that it outputs the XML with indentation. The following is an example of setting an option on the writer:

    if (FAILED(hr = pWriter->SetProperty(XmlWriterProperty_Indent, TRUE)))
        wprintf(L"Error, Method: SetProperty XmlWriterProperty_Indent, error is %08.8lx", hr);
        return -1;
  • To use the IXmlWriter, you repeatedly call methods to write various portions of the XML document.