O'Reilly logo

XSLT by Doug Tidwell

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

The document() Function

We’ll start with a couple of simple examples that use the document() function. We’ll assume that we have several purchase orders and that we want to combine them into a single report document. One thing we can do is create a master document that references all the purchase orders we want to include in the report. Here’s what that master document might look like:

<report>
  <title>Purchase Orders</title>
  <po filename="po38292.xml"/>
  <po filename="po38293.xml"/>
  <po filename="po38294.xml"/>
  <po filename="po38295.xml"/>
</report>

We’ll fill in the details of our stylesheet as we go along, but here’s what the shell of our stylesheet looks like:

<xsl:template match="/">
  <xsl:for-each select="/report/po">
    <xsl:apply-templates select="document(@filename)"/>
  </xsl:for-each>
</xsl:template>

In this template, we use the filename attribute as the argument to the document() function. The simplest thing we can do is open each purchase order, then write its details to the output stream. Here’s a stylesheet that does this:

<?xml version="1.0"?>--> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="html" indent="no"/> <xsl:strip-space elements="*"/> <xsl:template match="/"> <html> <head> <title><xsl:value-of select="/report/title"/></title> </head> <body> <xsl:for-each select="/report/po"> <xsl:apply-templates select="document(@filename)/purchase-order"/> </xsl:for-each> </body> </html> </xsl:template> <xsl:template match="purchase-order"> ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required