Returning XML from an ASPX page

Today I needed to make an ASPX page return a simple XML document with some basic server information.  The example below is over simplified but I think you can get the point.  This is pretty easy as it turns out.  Here are the steps:

  1. Create a new ASPX page in your solution just like you would any other page.
  2. Next remove everything from the markup except the @Page tag.  It should look like this an have nothing more:

 

  1. Here is a code snippet of the page load event that returns a simple XML element:

That's it.  I also found a nice post here that shows how to read XML from file and stream it back through the browser.  Pretty simple and useful.

Posted in |

3 comments:

  1. timheuer Says:

    Ben, if you have a UI-less Page, you should use a Generic handler so your page doesn't go through the full lifecycle...

  2. Ben H Says:

    Hey Tim, Thanks for the feedback!. You have a good point and I use HTTP handlers in other places in my app. However, in this case I knew my XML structure was going to be really basic and I didn't think it was worth creating a handler and all the config entries that go along with it. Plus, now I can just drop this page into any application I create and it works without any additional config setup. In short performance wasn't an issue so I chose simplicity.

  3. David Says:

    Do you know how to rename your aspx page to have an .xml extension and still return dynamic xml?