 | 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(); } } |