XmlViewControl - View XML in an ASP.NET Page

I have been meaning to put this up for awhile...  I see a lot of requests asking how to display XML within a web page.  Common answers range from using an IFRAME to performing come custom rendering.  Another one I see a lot uses the XmlDataDocument to sunch up an XmlDocument and DataSet, allowing binding to a DataGrid.

Here's yet another approach.  This control uses XSLT to transform an XML document and display it using HTML.

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.Reflection;

namespace Controls
{
[DefaultProperty("Text"),
ToolboxData("<{0}:XmlViewControl runat=server></{0}:XmlViewControl>")]
public class XmlViewControl : System.Web.UI.WebControls.WebControl
{
private string _innerXml;

[Bindable(true),
Category("Appearance"),
DefaultValue("")]
public string InnerXml
{
get
{
return _innerXml;
}

set
{
_innerXml = value;
}
}

/// <summary>
/// Render this control to the output parameter specified.
/// </summary>
/// <param name="output"> The HTML writer to write out to </param>
protected override void Render(HtmlTextWriter output)
{
output.RenderBeginTag(HtmlTextWriterTag.Div);
System.Xml.Xsl.XslTransform trans = new System.Xml.Xsl.XslTransform();

System.Xml.XmlDocument d = new System.Xml.XmlDocument();
d.LoadXml(GetStringResource("XmlViewXslt.xslt"));

trans.Load(d.CreateNavigator(),new System.Xml.XmlUrlResolver(),System.Xml.XmlSecureResolver.CreateEvidenceForUrl(System.Web.HttpContext.Current.Request.RawUrl ));

System.IO.StringReader x = new System.IO.StringReader(InnerXml);
System.Xml.XPath.XPathDocument doc = new System.Xml.XPath.XPathDocument(x);
trans.Transform(doc,null,output,null);
output.RenderEndTag();
}

private static string GetStringResource(string resourceName)
{
System.Reflection.Assembly thisAss;
string internalResName;
// string ret;
thisAss = System.Reflection.Assembly.GetExecutingAssembly();
internalResName = thisAss.GetName().Name + "." + resourceName;
string[] resNames;

try
{
resNames = thisAss.GetManifestResourceNames();
Array.Sort(resNames);

foreach (string Testname in resNames)
{
if ((string.Compare(Testname,internalResName, true)==0))
{
internalResName=Testname;
}
}
System.IO.Stream res = thisAss.GetManifestResourceStream(internalResName);
byte[] data = new Byte[res.Length];
res.Read(data,0,(int)res.Length);
return System.Text.ASCIIEncoding.ASCII.GetString(data);
}
catch
{
throw new Exception("String Resource '"+ resourceName + "' was not found");
}
}
}
}

This control uses a resource file that contains XSLT to render the document. Rather than list the XSLT resource document here, you can find Jonathan Marsh's original msxsml default stylesheet using XSLT online.

To package the project, copy Jonathan's XSLT to a file in your solution called "XmlViewXslt.xslt". In the Properties pane for the XSLT file, select the Build Action drop-down and change the value to "Embedded Resource".