TheDeveloperBlog.com

Home | Contact Us

CSharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript

ASP.NET OutputStream: XML

This C# tutorial uses XmlWriter in an ASP.NET page. It accesses the OutputStream property.

OutputStream is used to generate XML in ASP.NET.

We use OutputStream along with XmlWriter in an ASP.NET page. This will write XML directly into the page. This technique is helpful for XML sitemaps and RSS feeds.

Example. First, Response.OutputStream is a Stream object just like FileStream or many other versions in the .NET Framework. It can be written to in the same way. Response.End terminates the page.

Stream

Note: Response.End is called to stop any further content from being rendered. We pass OutputStream to the second method.

Response.Write

Page that uses OutputStream: ASP.NET

<%@ Page Language="C#" %>
<script runat="server" type="text/C#">
    protected void Page_Load(object sender, EventArgs e)
    {
	Response.ContentType = "text/xml";
	WriteGoogleMap("", Response.OutputStream);
	Response.End();
    }
</script>

Method that uses OutputStream: C#

public void WriteGoogleMap(string urlBase, Stream stream)
{
    XmlWriterSettings settings = new XmlWriterSettings();
    settings.Encoding = Encoding.UTF8;
    settings.Indent = true;
    using (XmlWriter writer = XmlWriter.Create(stream, settings))
    {
	writer.WriteStartDocument();
	writer.WriteStartElement("urlset", "http://www.sitemaps.org/schemas/sitemap/0.9");

	// Repeat this code:
	writer.WriteStartElement("url");
	writer.WriteElementString("loc", "[your url]");
	writer.WriteEndElement();

	writer.WriteEndElement();
	writer.WriteEndDocument();
    }
}

Example using Google sitemap. Here we make a Google sitemap using some of the above methods and objects. The code replaces the entire .aspx markup stored in the file with the output of code that writes to the Response.

It sets Response.ContentType to "text/xml". You need to do this for XML files like Google Sitemaps or RSS feeds. Internet Explorer can be difficult to deal with unless you do this right.

Next: A method called WriteGoogleMap is called. It is passed a string and a Stream object.

The second method writes XML to the Response.OutputStream. We construct an entire XML document. Because the OutputStream is set as the buffer for XmlWriter, when XmlWriter adds elements they are added to the Response.

So: The XmlWriter writes to Stream. When we use the XmlWriter to write XML to the page, it is added directly to the aspx page buffer.

Summary. We used OutputStream and XmlWriter to easily create dynamic XML files in aspx code-behind. It works well and the XML you create will be interoperable and usable in every web browser and compliant program.

Also: The OutputStream property can be passed to a method that receives a formal parameter of Stream type.

XmlWriter