Search code examples
asp.net

Display XML on an ASP.NET page


I have a string containing XML document using LinqtoXML

What is the best way of displaying it on an asp.net page as is.


Solution

  • I would have liked to do it the way Dennis has mentioned (using an <asp:Xml> control). But that necessitates the use of an XSL stylesheet to format the XML. The Xml control does not allow an HTML encoded string to be passed as the DocumentContent property and does not expose any method to encode the content.

    As I have mentioned in the comments to Dennis' post, the defaultss.xsl contained within msxml.dll is not available publicly (and is not XSL 1.0 compliant). However, a public converted version was posted here: http://www.dpawson.co.uk/xsl/sect2/microsoft.html#d7615e227. I have tested it and it works, though a bit buggy.

    Therefore, I think the simplest way would be to use an <asp:Literal> control to output pre-encoded XML to the page. The following sample demonstrates this method:


    <%@ Page Language="C#" %>
    
    <%@ Import Namespace="System.IO" %>
    <%@ Import Namespace="System.Xml" %>
    
    <script runat="server">
      protected void Page_Load(object sender, EventArgs e)
      {
        string theXML = Server.HtmlEncode(File.ReadAllText(Server.MapPath("~/XML/myxmlfile.xml")));
        lit1.Text = theXML;
      }
    </script>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
      <title>Untitled Page</title>
    </head>
    <body>
      <form id="form1" runat="server">
        <div>
          <pre>
            <asp:Literal ID="lit1" runat="server" />
          </pre>
        </div>
      </form>
    </body>
    </html>