XML technologies / XSLT / Introduction to XSLT 2.0 / XSLT and XPath – round three / External sources: documents and entities / Including documents with document()

(Excerpt from "XSLT 2.0 & XPath 2.0" by Frank Bongers, Chapter 3.)

The document() function allows external XML documents to be included in stylesheet processing, independently of the XML document being processed. It returns the document node of an external XML document.

Example: suppose book reviews exist as external XML files. You may want to include a review together with other information about the book in an output document. For example:

<buch>
   <rezension datum="14.10.2000" quelle="Tip" referenz="rezensionen/tip/14-10-2007/rez1.xml"/>
   <rezension datum="3.12.2000" quelle="Zitty" referenz="rezensionen/zitty/3-12-2007/rez8.xml"/>
</buch>

These reviews can now be fetched into the output document with the document() function by passing the URI in text , for example as follows:

<xsl:template match="buch">
<!-- die Rezension wird Current Node -->
  <xsl:for-each select="rezension">
    <h2>Rezension in <xsl:value-of select="@quelle"/></h2>
    <!-- der entspr. externe Text wird eingebunden: -->
    <xsl:apply-templates select="document(@referenz)"/>
  </xsl:for-each>
</xsl:template>

Here, @quelle is an attribute containing a URI as a text string.

A potential risk is that the referenced document uses the same element names with different meanings. In the example above, however, the same templates are used for both it and the including document.

One solution is to use different Namespaces for the two document types, or, preferably, to use the mode attribute when calling xsl:apply-templates, as follows:

<xsl:apply-templates select="document(@text)" mode="rezension" />

   

back to top