More Sophisticated Techniques
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 by all the customers. It might be useful to sort all the purchase orders by the state to which they were shipped, by the last name of the customer, or to group them by the state to which they were shipped. We’ll go through some of these scenarios to illustrate the design challenges we face when generating documents from multiple input files.
The document() Function and Sorting
Our first challenge will be to generate a listing of all purchase orders and sort them by 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:
<body> <h3>Selected Purchase Orders - <i>Sorted by state</i></h3> <xsl:for-each select="document(/report/po/@filename)/purchase-order/customer/address/state"> <xsl:sort select="."/> <xsl:apply-templates select="ancestor::purchase-order"/> </xsl:for-each> </body>
What makes this process slightly challenging is the fact that we’re sorting on one thing (the value of the <state>
element), then invoking <xsl:apply-templates>
against the <purchase-order>
ancestor of the ...
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.