home | articles | site map | contacts
about us
consulting
client login
support
contacts



  Exporting XML in a C# ASP .NET Web Application
Primary Objects C# .NET RSS Feed More C# ASP .NET
Articles by Primary Objects
enter email address
 

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.

 
Exporting XML in C# ASP .NET Web Applications

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:

<?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.

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.

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.

      // 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:

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, founder and chief developer of Primary Objects, a software and web application development company. You can contact Primary Objects regarding your software development needs at http://www.primaryobjects.com

  Post comment >
        
DateUserComment
11/28/2007aruna yes i am developing as per ur decision given. I am constructing an xml as well as am sending as a response.
But i am getting the error as "Only one top level element is allowed in an XML document. Error processing resource "

Please help me to resolve the same.

Thanks N Regards,
Aruna


11/28/2007K You can first try writing your generated XML to a file such as test.xml. Then open the file in Internet Explorer and see if it properly displays. If it doesn't, you should check your xml to make sure all tags have a matching start and end. That is, for each WriteStartElement you must also have a WriteEndElement and finally a WriteEndDocument. See the example at the top of this page for a complete XML file.

12/18/2007Aruna I am able to see the xml in IE. But i modified the code such as
for streaming xml to the webbrowser as stream and you are converting into bytes.

I am having a function,the same fucntionality i have returned as bytes itself.

Then while sending the http response,
the code is something like this,
HttpWebRequest request = (HttpWebRequest) HttpWebRequest.Create(url);
                  request.Method = "POST";
                  request.ContentType = "application/x-www-form-urlencoded";
                  byte[] byteArray = constructXML(); // function to construct an xml , it will return the stream as byte[]

                  if (byteArray != null)
                  {
                        request.ContentLength = byteArray.Length;
                     using (Stream requestStream = request.GetRequestStream())
                        {
                              requestStream.Write(byteArray, 0, byteArray.Length);
                              requestStream.Flush();
                        }
                     using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                  {
                        if (request.HaveResponse)
                        {
                              byteArray = new byte[response.ContentLength];
                              using (Stream responseStream = response.GetResponseStream())     
                                    responseStream.Read(byteArray, 0, byteArray.Length);
                        }
                  }
}

In the above code, i am getting the error as System.Net.WebException: The remote server returned an error: (500) Internal Server Error.


Am waiting for your earlier response.

I am not able to find out the exact problem.

Please help me in this...

Thanks in advance,
Aruna


3/12/2008Haranath Can anyone plz explain about SOAP actions in XML

4/16/2008david thnx for the help this article was very useful!   solved my woes of creating an xml file dynamically. ;-)


10/21/2008Sandy thanx for the artical...
its very ncie..

can u plz help me about reciving this file & geve response to it???


3/26/2009somalia thanks for this article.I was in search of it from many days and finally got it.It was a perfect solution for my requirement.

8/27/2009Khushi i have created the xml file and need to browse the same without downloading the file, i mean create and browse file directly.

Can anyone help me out plz, its very urgent..............


11/5/2009David Suarez Hi Kory,
thank you for the code. It worked nicely within our application.


Profile
Learn more about Primary Objects and our goals ..  More
12/22/2009
Primary Objects releases Linquify for .NET developers, LINQ to SQL library .. More
10/05/09
Primary Objects develops Prospect Tracking Portal for university .. More
Home | About Us | Services | Client Login | Job Opportunities | Contact Us
Copyright © Primary Objects 2009
Privacy Policy
Follow us on Twitter