Search code examples
c#asp.netxmlbrowserhttphandler

Display an XML in browser using data from DataTable + ASP.Net handler


I need to display XML in Browser, with these criteria:

  1. It should be through Handler for ASP.Net
  2. Data is coming from database directly which is stored in DataTable.
  3. Using this data table, I need to display XML in browser directly.

What I did is:

This code is written in ProcessRequest method where is final method is called. GetFeedData is where my SQL query is and returning table. The output for the table is also proper.

Or you can find:

private void BuildAYSONationalFeed(HttpContext context, string data)
{
    using (XmlTextWriter writer = new XmlTextWriter(context.Response.OutputStream, Encoding.UTF8))
    {
        DataTable dataTable = GetFeedData();

        MemoryStream str = new MemoryStream();
        dataTable.WriteXml(str, true);
        str.Seek(0, SeekOrigin.Begin);
        StreamReader sr = new StreamReader(str);
        string xmlstr;
        xmlstr = sr.ReadToEnd();

        context.Response.Clear();
        context.Response.Buffer = true;
        context.Response.Charset = "";
        context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        context.Response.ContentType = "application/xml";
        context.Response.Write("<?xml version='1.0' encoding='UTF - 8'?>< bookstore >< book >< title > Everyday Italian </ title >< author > Giada De Laurentiis </ author >< year > 2005 </ year >< price > 30.00 </ price ></ book ></ bookstore > ");
        context.Response.Flush();
        context.Response.End();
    }
}

Now, in xmlstr variable, I got the XML like this: I have minimised maximum nodes because of data privacy, but this is what I get in variable.

Now, when finally the response is written is displays like a plain HTLM without any formatting.

See here: Am I missing something? I tried to paste the same XML I get in xmlstr valiable to notepad and loaded it browser. It appears properly. To my best guess, I'm not able to get the proper data to stream.

Please let me know if anyone can help here with the same.


Solution

  • I got the solution by filling my DataTable to DataSet and the used the inbuilt function GetXML() from DataSet

    See the snippet below:

    private void BuildAYSONationalFeed(HttpContext context, DataTable feedDataTable)
        {
            DataSet dataSet = new DataSet("Portals");
            dataSet.Tables.Add(feedDataTable);
    
            context.Response.Clear();
            context.Response.ContentEncoding = Encoding.UTF8;
            context.Response.ContentType = "text/xml";
            context.Response.Write(dataSet.GetXml());
            context.Response.Flush();
            context.Response.End();
        }
    

    This did the job.

    So, GetXML() method basically loads the data stored as tabular format in DataSet to XML. I simply displayed the XML response to browser.