Archive for December, 2009

Transforming XML/XSLT using .NET 3.5

Here is a simple example of how you can apply a XSLT stylesheet to a XML file and deliver the result to the browser using ASP.NET 3.5.

default.aspx.cs

using System;
using System.IO;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;

public partial class _default : System.Web.UI.Page {

    protected void Page_Load(object sender, EventArgs e) {

        // Source paths
        string xmlFilePath = Server.MapPath("hello-world.xml");
        string xsltFilePath = Server.MapPath("hello-world.xslt");

        // Load XML
        XPathNavigator nav = new XPathDocument(new XmlTextReader(xmlFilePath)).CreateNavigator();

        // Stream for the transformed XML
        MemoryStream stream = new MemoryStream();

        // Load XSLT & transform
        XslCompiledTransform transformer = new XslCompiledTransform();
        transformer.Load(xsltFilePath);
        transformer.Transform(nav, null, stream);

        // Write output
        using (StreamReader reader = new StreamReader(stream)) {
            stream.Position = 0;
            Response.Write(reader.ReadToEnd());
            reader.Close();
        }

    }

}

Yes, that’s it! Here below are the rest of the code used to complete a fully working demo.

default.aspx


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="default.aspx.cs" Inherits="_default" %>

hello-world.xml

<?xml version="1.0" encoding="iso-8859-1"?>
<?xml-stylesheet type="text/xsl" href="hello-world.xslt"?>
<text>Hello World!</text>

hello-world.xslt

<?xml version="1.0" encoding="iso-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output indent="yes" />
  <xsl:output method="html"/>

  <xsl:template match="/">
<xsl:text disable-output-escaping="yes">
&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
</xsl:text>
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title><xsl:value-of select="text"/></title>
  </head>
  <body>
    <h1><xsl:value-of select="text"/></h1>
  </body>
</html>
  </xsl:template>

</xsl:stylesheet>

Tip! To have the HTML doctype declared in your XSLT document you need to wrap it in a <xsl:text> tag with the disable-output-escaping attribute set to yes. And don’t forget to swap the leading and tailing < and > for &lt; and &gt;.

Output

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>Hello World!</title>
  </head>
  <body>
    <h1>Hello World!</h1>
  </body>
</html>

,

No Comments