Exporting XML in a C# ASP .NET Web Application

modified

Introduction

XML (extensible markup language) is a popular format of data for importing and exporting between different applications designed using different programming languages. Since XML uses a standardized format of data, applications can easily parse the XML data to pull out specific fields, blocks, and even write their own XML files. XML is especially useful as a protocol for communicating over the Internet with applications (ie. SOAP). Given the flexibility of XML, it’s only a matter of time before your own C# ASP .NET web application may need the ability to import or export XML data to another application.

Distorted HTML

At a first glance, XML looks just like a web page in HTML. You can easily recognize beginning and ending tags. Brackets enclose each element’s name. The document usually has a header tag and a final closing tag. This makes using XML in a C# ASP .NET web application even easier. Note, while XML can be used to describe a particular object or data piece, it can also be used to export an entire class object or even an application state.

A basic XML document example is shown below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?xml version="1.0" encoding="us-ascii" ?>
<WebApplications>
  <WebApplication>
    <Date>8/3/2007 4:16:06 PM</Date>
    <Programmer>Primary Objects</Programmer>
    <Name>Hello World</Name>
    <Language>C# ASP .NET</Language>
    <Status>Complete</Status>
  </WebApplication>
  <WebApplication>
    <Date>8/4/2007 4:16:06 PM</Date>
    <Programmer>ksoft</Programmer>
    <Name>Records Database</Name>
    <Language>C# ASP .NET</Language>
    <Status>Complete</Status>
  </WebApplication>
</WebApplications>

It All Begins With a Memory Stream

You may be familiar with reading (consuming) an XML data source and exporting your own XML data from a C# ASP .NET web application is just as easy. Using the built-in C# .NET XML classes, we can easily create an XML file from a web application’s data and export the XML as a .xml file. The data can be streamed directly over the Internet to the web browser, without even creating a physical file.

To begin exporting an XML file, we start by creating an XML document in memory. In C# ASP .NET, we use the MemoryStream class to open a new file in memory.

1
2
3
4
5
6
7
8
9
10
using System.IO;
using System.Xml;

using (MemoryStream stream = new MemoryStream())
{
    // Create an XML document. Write our specific values into the document.
    XmlTextWriter xmlWriter = new XmlTextWriter(stream, System.Text.Encoding.ASCII);

    ...
}

In the above example, notice that we create a MemoryStream object. This is similar to creating a file on disk, but a physical file is never created. Since this is coming from a web applicaion, creating physical files on the fly is not preferred. Instead, streaming a data file from memory to the web browser is a more efficient and thread-safe method.

Exporting an XML File

Now that we have a memory stream available, we can begin writing XML data to it. XML is written using the .NET XmlTextWriter class. We can create actual XML object tags by using the WriteStartElement(), WriteElementString(), and WriteEndElement() functions. WriteStartElement writes a begin tag for an XML object. You could then write child XML objects below it and finally call WriteEndElement() to close the tag. WriteEndElement() remembers the XML data structure so that it automatically knows which closing tag to write at the time of calling. It’s important to keep track in your C# code of your XML structure so you know which tags are beginning and ending.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
using System.IO;
using System.Xml;

using (MemoryStream stream = new MemoryStream())
{
    // Create an XML document. Write our specific values into the document.
    XmlTextWriter xmlWriter = new XmlTextWriter(stream, System.Text.Encoding.ASCII);

    // Write the XML document header.
    xmlWriter.WriteStartDocument();

    // Write our first XML header.
    xmlWriter.WriteStartElement("WebApplications");

    // Write an element representing a single web application object.
    xmlWriter.WriteStartElement("WebApplication");

    // Write child element data for our web application object.
    xmlWriter.WriteElementString("Date", DateTime.Now.ToString());
    xmlWriter.WriteElementString("Programmer", "Primary Objects");
    xmlWriter.WriteElementString("Name", "Hello World");
    xmlWriter.WriteElementString("Language", "C# ASP .NET");
    xmlWriter.WriteElementString("Status", "Complete");

    // End the element WebApplication
    xmlWriter.WriteEndElement();

    // End the document WebApplications
    xmlWriter.WriteEndElement();

    // Finilize the XML document by writing any required closing tag.
    xmlWriter.WriteEndDocument();
}

In the above example, we create a simple XML file (the actual XML data was shown above in this article). Notice that our XML document contains two object tags. The first one represents the document’s contents, which contains “WebApplications”. The second tag represents a single “WebApplication” object. Inside the WebApplication are individual properties. You should be able to see how we could easily add a loop to iterate over a data source, exporting XML formatted data.

Streaming XML to the Web Browser

Now that we have an XML document in a memory stream, it can easily be streamed to a web browser and exported by using the Response object of the C# .NET web application. The process involves simply converting the memory stream to an array of bytes, setting up the HTML response header, and finally writing the bytes to the web browser in binary format. The end result is the web browser receiving an XML data source file and opening the file for the user. Note, most web browsers will automatically display the XML formatted data, rather than ask the user if they wish to save the file to disk.

1
2
3
4
5
6
7
8
9
10
11
12
13
// To be safe, flush the document to the memory stream.
xmlWriter.Flush();

// Convert the memory stream to an array of bytes.
byte[] byteArray = stream.ToArray();

// Send the XML file to the web browser for download.
Response.Clear();
Response.AppendHeader("Content-Disposition", "filename=MyExportedFile.xml");
Response.AppendHeader("Content-Length", byteArray.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.BinaryWrite(byteArray);
xmlWriter.Close();

The above code will flush the XML data to the memory stream and setup the HTTP response header for receiving a file. It then writes the XML bytes to the web browser in binary format. The web browser is able to receive a correctly formatted XML document.

A full example of the code, including streaming XML to the web browser, is shown below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
using System.IO;
using System.Xml;

protected void Page_Load(object sender, EventArgs e)
{
  using (MemoryStream stream = new MemoryStream())
  {
      // Create an XML document. Write our specific values into the document.
      XmlTextWriter xmlWriter = new XmlTextWriter(stream, System.Text.Encoding.ASCII);

      // Write the XML document header.
      xmlWriter.WriteStartDocument();

      // Write our first XML header.
      xmlWriter.WriteStartElement("WebApplications");

      // Write an element representing a single web application object.
      xmlWriter.WriteStartElement("WebApplication");

      // Write child element data for our web application object.
      xmlWriter.WriteElementString("Date", DateTime.Now.ToString());
      xmlWriter.WriteElementString("Programmer", "Primary Objects");
      xmlWriter.WriteElementString("Name", "Hello World");
      xmlWriter.WriteElementString("Language", "C# ASP .NET");
      xmlWriter.WriteElementString("Status", "Complete");

      // End the element WebApplication
      xmlWriter.WriteEndElement();

      // End the document WebApplications
      xmlWriter.WriteEndElement();

      // Finilize the XML document by writing any required closing tag.
      xmlWriter.WriteEndDocument();

      // To be safe, flush the document to the memory stream.
      xmlWriter.Flush();

      // Convert the memory stream to an array of bytes.
      byte[] byteArray = stream.ToArray();

      // Send the XML file to the web browser for download.
      Response.Clear();
      Response.AppendHeader("Content-Disposition", "filename=MyExportedFile.xml");
      Response.AppendHeader("Content-Length", byteArray.Length.ToString());
      Response.ContentType = "application/octet-stream";
      Response.BinaryWrite(byteArray);
      xmlWriter.Close();

  }
}

Conclusion

Through the use of XML formatted data, web applications can more easily communicate with each other, regardless of the programming language they were written in. By using C# ASP .NET, you can create communication-friendly web applications by exporting XML formatted data using the built-in .NET XML classes. Streaming XML to the web browser through the use of a memory stream is a powerful method for transfering dynamic data in a variety of formats. Using XML in your C# .NET web application, you can help other applications communicate with your own, building a better inter-connected world of software.

About the Author

This article was written by Kory Becker, software developer and architect, skilled in a range of technologies, including web application development, machine learning, artificial intelligence, and data science.

Share