Build a formatted XML document in memory in C#


This example uses an XmlTextWriter to build a formatted XML document in memory and displays it in a text box. When you click the Go button, the following code executes.

private void btnGo_Click(object sender, EventArgs e)
    MemoryStream memory_stream = new MemoryStream();
    XmlTextWriter xml_text_writer  = 
        new XmlTextWriter(memory_stream, System.Text.Encoding.UTF8);

    // Use indentation to make the result look nice.
    xml_text_writer.Formatting = Formatting.Indented;
    xml_text_writer.Indentation = 4;

    // Write the XML declaration.

    // Start the Employees node.

    // Write some Employee elements.
    MakeEmployee(xml_text_writer, "Albert", "Anders", 11111);
    MakeEmployee(xml_text_writer, "Betty", "Beach", 22222);
    MakeEmployee(xml_text_writer, "Chuck", "Cinder", 33333);

    // End the Employees node.

    // End the document.

    // Use a StreamReader to display the result.
    StreamReader stream_reader = new StreamReader(memory_stream);

    memory_stream.Seek(0, SeekOrigin.Begin);
    txtResult.Text = stream_reader.ReadToEnd();
    txtResult.Select(0, 0);

    // Close the XmlTextWriter.

This code makes a MemoryStream and an XmlTextWriter attached to it. The XmlTextWriter has methods such as WriteStartDocument, WriteStartElement, and WriteEndElement to create the pieces of the XML file.

The program sets the XmlTextWriter so it indents its output and then calls its WriteStartDocument method to start the XML document.

It calls the WriteStartElement method to create the <Employees> start tag. It then calls the MakeEmployee method several times to make Employee elements. It closes the Employees element by calling WriteEndElement to create the </Employees> end tag. It then closes the document by calling WriteEndDocument.

To display the result, the program makes a StreamReader attached to the MemoryStream. It moves to the beginning of the stream and uses the reader’s ReadToEnd method to read the stream’s contents.

The following code shows the MakeEmployee method.

// Add an Employee node to the document.
private void MakeEmployee(XmlTextWriter xml_text_writer, 
    String first_name, String last_name, int emp_id)
    // Start the Employee element.

    // Write the FirstName.

    // Write the LastName.

    // Write the EmployeeId.

    // Close the Employee element.

The MakeEmployee method simply uses the XmlTextWriter‘s WriteStartElement, WriteString, and WriteEndElement methods to build an Employee element.

Using an XmlTextWriter to build an XML document isn’t too hard, although it is long and you need to be sure to create end elements where they are needed.

Download Example   Follow me on Twitter   RSS feed

This entry was posted in XML and tagged , , , , , , , , , , , , , , . Bookmark the permalink.

1 Response to Build a formatted XML document in memory in C#

  1. Pingback: Use objects to make an XML document in C# -

Comments are closed.