I'm trying to add an XSL file reference to an existing code that generates an XML sitemap on the fly. There is no actual physical XML file as the code creates an XML response through a generic handler that responds to a url rewrite path (the handler is called SitemapProvider.ashx and handles requests to sitemap.xml). My end goal is to eventually style and decorate the boring sitemap.xml.
Here's a snippet of my code:
public void ProcessRequest(HttpContext context)
{
XmlDocument doc = ShowXML(context);
context.Response.ContentType = "text/xml";
context.Response.ContentEncoding = System.Text.Encoding.UTF8;
context.Response.Expires = -1;
context.Response.Cache.SetAllowResponseInBrowserHistory(true);
doc.Save(context.Response.Output);
}
private XmlDocument ShowXML(HttpContext context)
{
XmlDocument doc = new XmlDocument();
var useXSL = doc.CreateProcessingInstruction(
"xml-stylesheet", "type=\"text/xsl\" href=\"~/sitemap.xsl\""
);
doc.AppendChild(useXSL);
doc.LoadXml(makeXML());
return doc;
}
private string makeXML()
{
string xmlString = "";
xmlString +=
//"<?xml-stylesheet type=\"text/xsl\" href=\"/sitemap.xsl\"?>" +
"<urlset xmlns = \"http://www.sitemaps.org/schemas/sitemap/0.9\">" +
// and so it goes
I can't seem to get either the code in ShowXML() to work or the one I commented out in makeXML().
What am I doing wrong?
XmlDocument? Wouldn't it be easier to just generate a string with the XML you want and write it to the response directly?