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"> ...

Get XSLT now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.