How Return XML From ASPX in ASP.NET 1.1

I’m not sure if this is the “canonical” way to do it but here’s a description of how to write an ASP.NET 1.1 ASPX page which returns a XML document (e.g. when writing a home-brewed web service).

First, create a new Web Form (I will call it WebService.aspx). As we will be progamatically generating the XML in the HTTP response rather than sending the (processed) content of the ASPX file, delete everything from the ASPX file but the @Page directive, so that it looks something like:

<%@ Page language="c#" Codebehind="WebService.aspx.cs" AutoEventWireup="false"
    Inherits="WebService.WebService" %>

Next, open up the code-behind file WebService.aspx.cs. Within the Page_Load event handler, add the following code block:

private void Page_Load(object sender, System.EventArgs e)
    Response.ContentType = "text/xml";
    Response.ContentEncoding = Encoding.UTF8;

    using (TextWriter textWriter = new StreamWriter(Response.OutputStream,
        XmlTextWriter xmlWriter = new XmlTextWriter(textWriter);
        // Write XML using xmlWriter

Notice the use of the HttpResponse.OutputStream property which allows us to write directly to the HTTP response body. Also notice that I explicitly set the Content-Type and Content-Encoding HTTP response headers, and that the encoding for both the response and the StreamWriter must match.

Once you have this block in place, you can use whatever technique you like to write XML to the xmlWriter object. For example, you can call XmlWriter methods by hand, pass xmlWriter as a parameter to XslTransform.Transform(), or use the XmlSerializer.


XSLT Number Formatting Notes

When using XSLT’s format-number() function to format a decimal, consider using a zero in the least significant place of the decimal part of your format string. This will allow a number with a 0 integer part to display correctly.

For example:

Number format-number using #,### format-number using #,##0
12345 12,345 12,345
5 5 5
0 No output! 0

This also applies to decimals:

Number format-number using #.00 format-number using 0.00
5 5.00 5.00
0 .00 (Note no leading 0) 0.00
0.1234 .12 (Note no leading 0) 0.12