The document() Function and Sorting
Up to now, we’ve written a simple XML document that contains references to other XML documents, then we created a stylesheet that combines all those referenced XML documents into a single output document. That’s all well and good, but we’ll probably want to do more advanced things. For example, it might be useful to generate a document that lists all items ordered across all purchase orders. It might also be useful to sort all the purchase orders by the state to which they were shipped or by the last name of the customer. We’ll go through some of these scenarios to illustrate the design challenges we face when generating documents from multiple input files.
Our first challenge will be to generate a listing of all purchase
orders and sort them by state, then by city within state. This isn’t
terribly difficult; we’ll simply use the <xsl:sort> element in conjunction with the document() function. Here’s the heart of
our new stylesheet:
<?xml version="1.0"?>
<!-- masterdox2.xsl -->
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
...
<xsl:apply-templates
select="document(/report/po/@filename)/purchase-order">
<xsl:sort select="customer/address/state"/>
<xsl:sort select="customer/address/city"/>
</xsl:apply-templates>Here we’re selecting all of the <purchase-order> elements and sorting
them by the values of their <state> and <city> elements. Figure 8-2 shows our output document, sorted by the
value of the <state> element ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access