I have been architecting and developing solutions for many years and have benefited a lot from the internet. I can't tell you the number of times searching for something has saved me countless hours. There are so many cool articles and cool people writing them. This is why I decided to write my first article - to give back to a community that has given me a lot. Also, because I spent a few hours searching for a way to display an XML string in a similar way to the way Internet Explorer does it.
I am surprised that although much of modern technology depends on XML, the webBrowser control does not natively allow you to view XML the way Internet Explorer does (unless you are viewing an XML File). Having to rely on the presence of an XML file to view formatted XML is not at all desireable.
As with many development endeavours, hours (about two days) of research went into this one and the lines of code are surprisingly few.
My journey began by discovering an XSL file that was using the old unsupported XSL namespace "http://www.w3.org/TR/WD-xsl". Efforts to modernize this to XSLT 2.0 were not completely fruitful due to the lack of a simple way to select and render namespaces and cdata sections.
Luckily, today I remembered the old way of doing things (FreeThreadedDOMDocument and the good old XSLTemplate). The old XSL processor can still be used in .NET. That was the break I needed.
Using the code
The code for this article consists of two projects XmlRender and XmlRenderTestApp.
| Name |
Description |
XmlRender |
This project contains one static class method RenderXmlToHtml.Render(string xmlToRender) |
XmlRenderTestApp |
This project contains a webform with a dropdown to select two XML Files. Each file is passed as a string to the XmlRender static class method to render it as HTML before sending it to the browser |
XmlRenderCode:
Collapse
public static class RenderXmlToHtml
{
public static string Render(string xmlToRender)
{
XSLTemplate oXSLT = new XSLTemplate();
FreeThreadedDOMDocument oStyleSheet = new FreeThreadedDOMDocument();
IXSLProcessor oXSLTProc;
DOMDocument oXMLSource = new DOMDocument();
oStyleSheet.async = false;
oStyleSheet.loadXML(XmlRender.Properties.Resources.XMLToHTML);
oXSLT.stylesheet = oStyleSheet;
oXSLTProc = oXSLT.createProcessor();
oXMLSource.async = false;
oXMLSource.loadXML(xmlToRender);
oXSLTProc.input = oXMLSource;
oXSLTProc.transform();
return oXSLTProc.output.ToString();
}
XmlRenderTestApp code:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
System.Xml.XmlDocument xd = new System.Xml.XmlDocument();
xd.Load(new System.IO.FileInfo(
System.Reflection.Assembly.GetExecutingAssembly().FullName
).DirectoryName + @"\XML Files\" + comboBox1.SelectedItem.ToString());
webBrowser1.DocumentText = XmlRender.RenderXmlToHtml.Render(xd.OuterXml);
}