Click here to Skip to main content
13,662,961 members
Click here to Skip to main content
Add your own
alternative version


39 bookmarked
Posted 12 Mar 2008
Licenced CPOL

XML String Browser (just like Internet Explorer) using the WebBrowser Control

, 14 Apr 2008
Rate this:
Please Sign up or sign in to vote.
This article will show you how to view a colourful collapsible treeview for XML Strings/XmlDocument in a browser (just like Internet Explorer) without the need for XML files.


This article will show you how to render an XML string or System.Xml.XmlDocument the same way Internet Explorer renders an XML file. On the surface, this seems like a simple task. Wrong! If you believe that this is a simple task, you would be surprised how wrong you would be (I was). The user control in this example is useful because a lot of modern technologies depend on XML. As such, the absence of a simple way to display intermediate or generated XML in a presentable format is not satisfactory. That's why I created this control - because I couldn't find one like this one anywhere! Ever wondered how to display a formatted XML string or XML document without the need for an XML file? Do you despair, like I did, because the WebBrowser control doesn't present a simple way to do this? If so, look no further - this article presents the answer you seek.

The following screenshot depicts the rendering of a sample XML file. The file is loaded into a string before rendering.



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 way similar to how Internet Explorer does it.

I am surprised that although a lot of modern technologies depend 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 desirable.

As with many development endeavors, hours (several days) of research went into this one.

My journey began by discovering an XSL file (referred to as DEFAULTSS.XSL) that was using the old unsupported XSL namespace "". Efforts to modernize this to XSLT 1.0 were, initially, not completely fruitful due to the lack of a simple way to select and render namespaces and CData sections.

Luckily, 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. After that, I made important (and challenging) changes to complete an XSLT 1.0 version of the DEFAULTSS.XSL file (used by Internet Explorer to render XML files). This version was originally converted by Steve Muench, and can be found here.

Since I first wrote this article, I've tried a couple of new ways to render XML. One includes using the SAXON parser (XSLTHtml20.xslt); the other way (which I believe is the best way) includes using the namespace axis and escaping CData nodes before passing to XSLT transformation (XmlToHtml10Basic.xslt).

Using the code

The code for this article consists of two projects, XmlRender and XmlRenderTestApp.

XmlRenderThis project contains a few static class methods:
  • RenderXmlToHtml.Render(XmlDocument xmlToRender,XmlRender.XmlBrowser.XslTransformType xslTransformType)
  • RenderXmlToHtml.Render(System.Xml.XmlDocument xmlToRender)
  • RenderXmlToHtml.Render(string xmlToRender)

It also contains the XmlBrowser control which extends the WebBrowser with three settings:

  • System.Xml.XmlDocument XmlDocument
  • string XmlText
  • XmlRender.XmlBrowser.XslTransformType

All of these properties are used to indicate to the browser that we would like to display formatted XML (and how it should be rendered).

XmlRenderTestAppThis project contains a web form with a dropdown to select XML files, radio buttons to indicate whether or not we want to use an XSL or XSLT transformation, and the XmlBrowser control. Each file is loaded into a string, and sets the XmlDocument property of the XmlBrowser.

XmlRender code:

/// <span class="code-SummaryComment"><summary /></span>
/// This class has the methods required to render XML as pretty HTML.
/// <span class="code-SummaryComment"></summary /></span>
internal static class RenderXmlToHtml
    #region Render(XmlDocument xmlToRender, 
            XmlBrowser.XslTransformType xslTransformType)
    /// <span class="code-SummaryComment"><summary></span>
    /// This method determines which output type to render
    /// <span class="code-SummaryComment"></summary></span>
    internal static string Render(XmlDocument xmlToRender, 
             XmlBrowser.XslTransformType xslTransformType)
        if (xslTransformType == XmlBrowser.XslTransformType.XSL)
            return Render(xmlToRender.OuterXml);
        else if (xslTransformType == XmlBrowser.XslTransformType.XSLT10)
            return Render(xmlToRender,XmlRender.Properties.Resources.XmlToHtml10);
        else if (xslTransformType == XmlBrowser.XslTransformType.XSLT10RegExp)
            return Render(xmlToRender,
        return string.Empty;

    #region Render(string xmlToRender)
    /// <span class="code-SummaryComment"><summary></span>
    /// This method has to use the old XSL Processor because of the fact that the
    /// namespace is unsupported.
    /// The simplest way was to use the old xsl instead of re-inventing the wheel.
    /// I could not find a way to easily fully convert this to XSLT 1.0 due to 
    /// the lack of namespace and cdata 'selectability'.
    /// This brings back memories :)
    /// <span class="code-SummaryComment"></summary></span>
    internal static string Render(string xmlToRender)
        XSLTemplate oXSLT;
        FreeThreadedDOMDocument oStyleSheet;
        IXSLProcessor oXSLTProc;
        DOMDocument oXMLSource;

            oXSLT = new XSLTemplate();
            oStyleSheet = new FreeThreadedDOMDocument();
            oXMLSource = new DOMDocument();

            oStyleSheet.async = false;

            oXSLT.stylesheet = oStyleSheet;

            oXSLTProc = oXSLT.createProcessor();

            oXMLSource.async = false;
            oXSLTProc.input = oXMLSource;


            return oXSLTProc.output.ToString();
        catch (Exception e)
            return e.Message;
            oXSLT = null;
            oStyleSheet = null;
            oXMLSource = null;
            oXSLTProc = null;

    #region Render(XmlDocument xmlToRender)
    /// <span class="code-SummaryComment"><summary></span>
    /// This method uses the XsltCompiledTransform to transform XML to pretty HTML.
    /// Unfortunately, this method does require
    /// using EXSL/MSXML but it is XSLT 1.0 compliant.
    /// <span class="code-SummaryComment"></summary></span>
    internal static string Render(XmlDocument xmlToRender,string xsltDocument)
        XslCompiledTransform xslCompiledTransform;
        XmlReader xmlReader;
        System.IO.StringReader stringReader;
        StringBuilder stringBuilder;
        XmlWriter xmlWriter;
        XsltSettings xsltSettings;
            xslCompiledTransform = new XslCompiledTransform(true);
            stringReader = new System.IO.StringReader(xsltDocument);
            xmlReader = XmlReader.Create(stringReader);
            xsltSettings = new XsltSettings(true, true);
            xslCompiledTransform.Load(xmlReader,xsltSettings,new XmlUrlResolver());

            stringBuilder = new StringBuilder();
            xmlWriter = XmlWriter.Create(stringBuilder);
            XsltArgumentList a = new XsltArgumentList();
            // Need to pass the xml string as an input parameter so
            // we can do some parsing for extra bits that XSLT won't do.
            a.AddParam("xmlinput", string.Empty, xmlToRender.OuterXml);
            xslCompiledTransform.Transform(xmlToRender, a, xmlWriter);
            return stringBuilder.ToString();
        catch (Exception e) { return e.Message; }
            xslCompiledTransform = null;
            xmlReader = null;
            stringReader = null;
            stringBuilder = null;
            xmlWriter = null;
            xsltSettings = null;

XmlRenderTestApp code:

public partial class Form1 : Form
    // used to store location of xml files
    string _xmlDirectory;

    #region Constructor
    /// <span class="code-SummaryComment"><summary></span>
    /// Constructor
    /// <span class="code-SummaryComment"></summary></span>
    public Form1()
        // Set up xmlDirectory and load combo box. 
        // when you build the project all files are copied to $(TargetDir)\XML Files
        // just add any additional files you want to the XML files directory of this project
        FileInfo fi = new FileInfo(Assembly.GetExecutingAssembly().FullName);
        _xmlDirectory = fi.DirectoryName + @"\XML Files\";
        foreach(FileInfo file in new DirectoryInfo(_xmlDirectory).GetFiles("*.*"))

    #region comboBox select
    /// <span class="code-SummaryComment"><summary></span>
    /// Xml file to load into a string for rendering.
    /// <span class="code-SummaryComment"></summary></span>
    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        XmlDocument _xd;
            _xd = new XmlDocument();
            string fileName = _xmlDirectory + comboBox1.SelectedItem.ToString();
            System.Uri _uri = new Uri(fileName);


            // the following lines are of particular interest. 
            // I'm rendering an XML string to HTML (using good old XSL).
            // This gives us the flexibility to build XML and 
            // present it in the browser in a nice way.
            // I have to do this because we can't send an XML string to the browser 
            // and expect it to render like IE does

            // Send an XmlDocument to the XmlBrowser
            xmlBrowser1.XmlDocument = _xd;

            // Uncomment the following to send Xml Text to the XmlBrowser
            //xmlBrowser1.XmlText = _xd.OuterXml;

            // Uncomment the following to see how
            // the webbrowser control renders XML text
            //xmlBrowser1.DocumentText = _xd.OuterXml;

            // Uncomment the following to compare
            // to WebBrowser native rendering of Xml Documents
            //xmlBrowser1.Url = _uri;
            _xd = null;

    #region RadioButtons
    private void radioButton1_CheckedChanged(object sender, EventArgs e)
        xmlBrowser1.XmlDocumentTransformType = 

    private void radioButton2_CheckedChanged(object sender, EventArgs e)
        xmlBrowser1.XmlDocumentTransformType = 
    private void radioButton3_CheckedChanged(object sender, EventArgs e)
        xmlBrowser1.XmlDocumentTransformType = 


XmlBrowser code:

// Use this control if you want a webBrowser which has been extended 
// to allow for Xml Rendering
public partial class XmlBrowser : WebBrowser
    #region Types/Private Variables
    /// <span class="code-SummaryComment"><summary></span>
    /// Type to determine which XSL/XSLT to use in transformation
    /// <span class="code-SummaryComment"></summary></span>
    public enum XslTransformType
    // XmlDocument to store Xml data for rendering
    private XmlDocument _xmlDocument;
    // XslDocument to use when rendering Xml
    private XslTransformType _xslTransformType;

    #region Constructor
    public XmlBrowser()

    #region Properties

    #region XmlText
    /// <span class="code-SummaryComment"><summary></span>
    /// Property to set Xml Text for webbrowser
    /// <span class="code-SummaryComment"></summary></span>
    [Description("Use this property to set the XmlText 
                  for rendering in the webbrowser.")]
    public string XmlText
            if (value != string.Empty)
                _xmlDocument = new XmlDocument();
                this.DocumentText = 
            if (_xmlDocument == null)
                return string.Empty;
                return _xmlDocument.OuterXml;

    #region XmlDocument
    /// <span class="code-SummaryComment"><summary></span>
    /// Property to set XmlDocument for webbrowser
    /// <span class="code-SummaryComment"></summary></span>
    [Description("Use this property in your code to set the 
          System.Xml.XmlDocument for rendering in the webbrowser.")]
    public XmlDocument XmlDocument
            return _xmlDocument;
            if (value != null)
                _xmlDocument = value;
                this.DocumentText = 

    #region XmlDocumentTransformType
    /// <span class="code-SummaryComment"><summary></span>
    /// Change this to determine which transform type to use
    /// <span class="code-SummaryComment"></summary></span>
    [Description("Use this property to specify to use either 
       the XSL or XSLT 1.0 compliant stylesheet for rendering.")] 
    public XslTransformType XmlDocumentTransformType
            return _xslTransformType;
            _xslTransformType = value;


Points of interest

I thought about listing the XmlToHtml10.xslt/XmlToHtml10Plus.xslt file(s) here, but they are pretty big. I will tell you about the highlights though:

  • XmlToHtml10.xslt does use MSXML2.FreeThreadedDOMDocument a little bit in the JavaScript (I initially thought about using Regular Expressions, but I didn't do this at first because I didn't want to spend a lot of time writing this article).
  • XmlToHtmlPlus.xslt only uses Regular Expressions. It does not use MSXML2.FreeThreadedDOMDocument. This is particularly good because I'm thinking that it might be more efficient.
  • There is some clever use of XPath building in the XSLT to identify the current context node to the JavaScript function. (See the section on CDATA handling.)
  • For some interesting examples of XSLT recursion, take a look at the xmlnsSelector template or the getXPath template. XSLT recursion is always fun.
  • Last but not least, if you debug/show the output of XmlToHtml10.xslt/XmlToHtml10Plus.xslt in VS2005, it won't take advantage of the interesting bits I've added. You can only see this at runtime.

I actually was writing another article to demonstrate how easy it is to shape a DataSet with table data retrieved from any database by supplying an XSD at run-time to a generic DataSet. The lack of XML viewability caused me to get side-tracked and write this article first! You can find the article I am referring to here.

I hope you like this article. I really enjoyed thinking about the challenges it presented.

Here is a brief overview of the transformation files included in this project:

NameXSLT ProcessorUses ExtensionsDescription
XMLToHTML.xslXSLNoOriginal Microsoft XSL
XMLToHTML10.xsltXSLT1.0YesUses FreeThreadDomDocument/Regular Expressions with XSLT to get at namespace nodes and CDATA
XMLToHTML10Plus.xsltXSLT1.0YesUses only Regular Expressions to get at CDATA and namespace nodes
XMLToHTML10Cdata.xsltXSLT1.0YesUses Regular Expressions to get at CDATA, and namespace axis to get at namespaces
XMLToHTML10Basic.xsltXSLT1.0NoUses escaping of CDATA and namespace axis
XMLToHtml20.xsltXSLT2.0NoNo rendering of namespaces or CDATA

A general point - the transformations that don't use JavaScript extensions perform better than the ones that do.


  • 12-Mar-2008
  • Initial release.

  • 13-Mar-2008
  • Fixed a rendering issue so that an XML string now displays exactly like Internet Explorer viewing an XML document. Added the XMLBrowser control with two properties: XmlDocument and XmlText. This is to encapsulate XML formatting to a reusable user control within the XmlRender class library.

  • 17-Mar-2008
  • Added the XSLT equivalent for DEFAULTSS.XSL. Also, added some checkboxes to the test app to allow toggling between XSL/XSLT transformation.

  • 18-Mar-2008
  • Modified form to automatically populate based on files in the $(TargetDir)\XML Files directory. Files are automatically copied to this directory when building the project (via build events). No need to set build options on each file (just copy them to the XML files directory in the XmlRenderTestApp project.

  • 24-Mar-2008
  • Added the Regular Expression only version of the XSLT file (called XmlToHtml10Plus.xslt). Also, made a slight correction to the XmlToHtml10.xslt, for consistency.

  • 26-Mar-2008
  • Minor fix to XmlToHtml10Plus.xslt and XmlToHtml10.xslt with regards to xmlns-like attributes.

  • 04-Apr-2008
  • Added SAXON implementation of XML rendering - still a work in progress, but has really cool functionality.

  • 07-Apr-2008
  • Large XML option using the Microsoft XSLT parser will not add namespaces and CDATA nodes. Very quick.

  • 14-Apr-2008
  • Large XML option using the Microsoft XSLT parser will add namespaces and CDATA nodes. Very quick. Uses the namespace axis and escaping of CDATA so that it can be used in XSLT.



This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

George Zabanah
Australia Australia
George Zabanah has been architecting and developing solutions commercially from start to finish for over 11 years. He has been programming since he was 11 (for over 25 years now!) using many different technologies (almost all Microsoft). George is proficient in many languages and employs best practices wherever possible using design patterns, .NET, XSLT, XML, Regular Expressions, various flavours of SQL (to name just a few). His favourite tools, however, are the whiteboard and Sparx Enterprise Architect/Powerpoint. Many waking moments have been spent by George thinking about solutions in his head (even while watching tv). His best moments are the "Eureka" moments when he wakes up from a good sleep (or after watching tv) to find that his latest challenge has been solved!

You may also be interested in...


Comments and Discussions

QuestionThnx Pin
Marinos Chrstoforou16-Feb-12 3:42
memberMarinos Chrstoforou16-Feb-12 3:42 
GeneralMy vote of 4 Pin
Hardryv27-Oct-11 9:09
memberHardryv27-Oct-11 9:09 
GeneralGreat Pin
michaelnelson123454-May-11 6:32
membermichaelnelson123454-May-11 6:32 
GeneralProgrammatic expand/collapse of nodes Pin
Member 14612357-Dec-10 6:05
memberMember 14612357-Dec-10 6:05 
GeneralThanks! Pin
artcolman19-Mar-10 3:29
memberartcolman19-Mar-10 3:29 
GeneralRe: Thanks! Pin
George Zabanah24-Mar-10 14:25
memberGeorge Zabanah24-Mar-10 14:25 
GeneralXMLBrowser Pin
Marc Mueller8-Aug-08 3:31
memberMarc Mueller8-Aug-08 3:31 
GeneralRe: XMLBrowser Pin
Marc Mueller8-Aug-08 3:36
memberMarc Mueller8-Aug-08 3:36 
GeneralThanks Pin
k.bogucarskis9-Jun-08 3:35
memberk.bogucarskis9-Jun-08 3:35 
QuestionXML Editing Pin
YoniP5-May-08 1:29
memberYoniP5-May-08 1:29 
AnswerRe: XML Editing Pin
George Zabanah5-May-08 23:08
memberGeorge Zabanah5-May-08 23:08 
GeneralMuch more easy in ASP.NET Pin
marqis12-Apr-08 23:29
membermarqis12-Apr-08 23:29 
GeneralRe: Much more easy in ASP.NET Pin
George Zabanah13-Apr-08 13:35
memberGeorge Zabanah13-Apr-08 13:35 
GeneralGreat improvement Pin
robvon18-Mar-08 11:04
memberrobvon18-Mar-08 11:04 
GeneralRe: Great improvement Pin
George Zabanah18-Mar-08 12:33
memberGeorge Zabanah18-Mar-08 12:33 
GeneralAdding xml files to the test Pin
robvon17-Mar-08 20:34
memberrobvon17-Mar-08 20:34 
GeneralRe: Adding xml files to the test Pin
George Zabanah17-Mar-08 20:57
memberGeorge Zabanah17-Mar-08 20:57 
AnswerRe: Adding xml files to the test Pin
George Zabanah18-Mar-08 1:30
memberGeorge Zabanah18-Mar-08 1:30 
AnswerNot hard to view anymore Pin
George Zabanah12-Mar-08 13:21
memberGeorge Zabanah12-Mar-08 13:21 
GeneralRe: Not hard to view anymore Pin
smesser12-Mar-08 17:21
membersmesser12-Mar-08 17:21 
GeneralHard to view Pin
George Zabanah12-Mar-08 10:14
memberGeorge Zabanah12-Mar-08 10:14 
GeneralCompare your results to opening the same files in Internet Explorer Pin
smesser12-Mar-08 6:15
membersmesser12-Mar-08 6:15 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web01-2016 | 2.8.180810.1 | Last Updated 14 Apr 2008
Article Copyright 2008 by George Zabanah
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid