Home > Articles > Programming > Windows Programming

  • Print
  • + Share This
Like this article? We recommend

XSLT and XslTransform

XSLT defines a transformation language used to convert an XML document into another document through a set of imperative rules and templates. The XslTransform class is the workhorse of XSLT in .NET that provides such functionality. It supports transforming any document source that supports IXPathNavigable, confirming the primacy of that important interface. If you are interested in just doing an XSLT transform, XPathDocument shines as the most resource-efficient document source.

XslTransform implements a simple set of methods. The Load method does the loading, and the Transform method creates the final output. The example in Listing 7 shows how it works its magic. The source document is loaded into an instance of XPathDocument, while an instance of the XslTransform class loads up the XSLT document. Listing 6 shows the XSLT document that we use to transform our PO.xml document into a nicely formatted text table. For output purposes, we set up an XmlTextWriter that is piped to the console. This writer is passed to the Transform method of XslTransform along with the source XPathDocument to produce the output shown in Listing 8.

Listing 6: PO.xslt

<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/ Transform">

<xsl:template match="/">
Purchase Order
Number: <xsl:value-of select="//Number" />
Order Date: <xsl:value-of select="//OrderDate" />

Line Items
<xsl:apply-templates select="//LineItem" />

<xsl:template match="LineItem">
Name:<xsl:value-of select="@Name"/> 
Qty:<xsl:value-of select="@Qty"/>
Price:<xsl:value-of select="@Price"/>


Listing 7: XSLT Demo

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

namespace XmlDotNet

public class XsltDemo

public static void Main()
   // load up the XML document source using the 
   // XPathDocument class for efficiency in the
   // transform process
   XPathDocument doc = new XPathDocument("PO.xml");
   // load up the XSLT transformation document
   XslTransform xslt = new XslTransform();
   // configure a writer to pump output to the
   // console
   XmlTextWriter writer = new XmlTextWriter(Console.Out);
   // transform the document and output to console
   xslt.Transform(doc, null, writer);


Listing 8: XSLT Demo Results

Purchase Order
Number: 1001
Order Date: 8/12/01

Line Items

Name:Computer Desk Qty:1 Price:499.99
Name:Monitor Qty:1 Price:299.99
Name:Computer Qty:1 Price:999.99
Name:Mouse Qty:1 Price:49.99
  • + Share This
  • 🔖 Save To Your Account