Tuesday, December 18, 2007

XML paging using XML + XSL + CSS

CodeProject: XML paging using XML + XSL + CSS 28 Jan 2004

Introduction

Hello again, I decided to take a break from graphics and do some XML. I created an XML Pager, what it does is read an XML file and apply an XSL translation and send params to it to create a paged document.

Important, you need to have ASP.NET 1.1 running on your server! ASP.NET 1.0 had a bug in the XSL module. If you have 1.0 and try to run this, Windows will report a call to a nonexistent function.

How it's done

All you have to do is create a new XmlDocument object and an XslTransform object. Load them with data and call the Transform method. Below is a sample:

Dim xmlDoc As New XmlDocument
Dim xslDoc As New XslTransform

xmlDoc.Load("mydoc.xml")
xslDoc.Load("mydoc.xsl")

xslDoc.Transform(xmlDoc, nothing, Response.OutputStream, Nothing)

Sending Params to the XSL

Everything is exactly the same as the above example except that you create another object called XsltArgumentList.

Dim xmlDoc As New XmlDocument
Dim xslDoc As New XslTransform
Dim xslArgs as new XsltArgumentList

xmlDoc.Load("mydoc.xml")
xslDoc.Load("mydoc.xsl")

xsltParams.AddParam("start", "", 1)
xsltParams.AddParam("end", "", 5)
xslDoc.Transform(xmlDoc, xsltParams, Response.OutputStream, Nothing)

The XSL File

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">http://www.w3.org/1999/XSL/Transform">
<xsl:param name="start"/>
<xsl:param name="end"/>
<xsl:param name="link"/>

<xsl:template match="/">
<html>
<head>
<link href="guestbook.css" rel="stylesheet" type="text/css" />
</head>
<body>
<xsl:for-each
select="//guestbook/entry[position()>=$start and $end>=position()]">

<div id="guestbook">
<div class="head"><xsl:value-of select="title"/></div>
<div class="body"><xsl:value-of select="text"/></div>
<div class="footer">
<xsl:value-of select="date"/> <xsl:value-of select="email"/></div>
</div>
</xsl:for-each>
<xsl:value-of select="$link" disable-output-escaping="yes"/>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

You specify the params at the top of the file and then just use them like regular vars.