What Is the XSLT 1.0 document() Function Used For?

The document() function in XSLT 1.0 enables stylesheets to access and process XML data from external files, secondary sources, or multiple documents within a single transformation. While standard XSLT processing operates on a single primary input source, document() breaks this limitation by loading external XML trees dynamically via URIs. This capability is essential for multi-document workflows such as merging separate data sources, performing cross-reference lookups, managing modular configuration files, and batch processing collections of XML files.

Overcoming Single-Input Limitations

By default, an XSLT transformation receives one principal XML document and navigates its node tree. In enterprise workflows, data is frequently distributed across multiple files—such as separate catalog, customer, and localization resources.

The document() function allows an XSLT processor to retrieve nodes from external resources, returning a node-set corresponding to the root of the targeted document. Once loaded, these external nodes can be traversed, filtered, and transformed using standard XPath expressions, just like the primary input document.

Syntax and URI Resolution

The function supports one or two arguments to locate and load resources:

When supplied with a node-set containing multiple URI values, document() resolves each URI and returns a combined node-set containing the root nodes of all referenced documents. Supplying an empty string as the argument—document('')—references the stylesheet document itself, allowing templates to read embedded lookup tables or metadata directly.

Common Use Cases

1. Data Aggregation and Merging

When separate XML files hold related information, the document() function pulls these disparate streams into a unified output structure. For instance, an order report can iterate over invoice items from the main document while fetching full item descriptions from an external catalog.xml file.

<xsl:variable name="catalog" select="document('catalog.xml')"/>
<xsl:template match="order-item">
  <item>
    <id><xsl:value-of select="@sku"/></id>
    <name><xsl:value-of select="$catalog/products/product[@id=current()/@sku]/name"/></name>
  </item>
</xsl:template>

2. Localization and Reference Lookups

Dynamic translation workflows rely on external dictionary XML files containing locale-specific strings. The stylesheet accesses messages_en.xml or messages_es.xml based on a parameter, retrieving translated labels without hardcoding values into the transform logic.

3. Processing Document Manifests

Workflows often require transforming a collection of XML files listed inside an index or manifest file. A stylesheet can iterate over each entry in the manifest, load the corresponding file using select="document(@href)", and apply uniform templates across all files in a single pass.

Core Processing Considerations