views:

82

answers:

1

My HttpHandler looks like:

public void ProcessRequest(HttpContext context)
{
    context.Response.ContentType = "text/xml";


    XmlWriter writer = new XmlTextWriter(context.Response.OutputStream, Encoding.UTF8);

    writer.WriteStartDocument();
    writer.WriteStartElement("ProductFeed");

    DataTable dt = GetStuff();

    for(...)
    {

    }         



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


    writer.Flush();
    writer.Close();                

}

How can I cache the entire xml document that I am generating?

Or do I only have the option of caching the DataTable object?

+1  A: 

Several things:

  1. Do not use XmlTextWriter unless you're still using .NET 1.1. Use XmlWriter.Create() instead.
  2. Your use of the XmlWriter needs to be in a using block, or you'll have resource leaks when an exception is thrown. That's very bad for something like an HttpHandler, since it can be called many times.
  3. You can create a MemoryStream to base your XmlWriter on. Create the XML as you currently are, but when you're done, you can "rewind" the MemoryStream by setting the Position to 0. You can then write the contents of the stream to a file, or wherever you like.
John Saunders
I want to store it in cache, not file. Can you help me out with #3? sounds interesting...
Blankman
oh, with XmlWriter I can save to a stringbuilder, and maybe cache that?
Blankman
@Blankman: yes, caching the result of a StringBuilder would work.
John Saunders