A More Advanced Example

Our final example triplet of source document, stylesheet, and result document involves converting an XML format into another XML format, rather than HTML. Example B-7 shows a simple XML document containing order information.

Example B-7. An XML document containing orders

<orders>
  <order>
    <item>Widget</item>
    <price>50</price>
    <quantity>3</quantity>
  </order>
  <order>
    <item>Thingamajig</item>
    <price>25</price>
    <quantity>2</quantity>
  </order>
  <order>
    <item>Whatchamacallit</item>
    <price>35</price>
    <quantity>1</quantity>
  </order>
</orders>

Example B-8 shows an XSLT stylesheet for converting this document into a summary format.

Example B-8. An XSLT stylesheet for processing orders

<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
   
  <xsl:output indent="yes"/>
   
  <xsl:template match="/">
    <orderSummary>
      <expensiveItems>
        <xsl:apply-templates select="/orders/order[price >= 30]"/>
      </expensiveItems>
      <cheapItems>
        <xsl:apply-templates select="/orders/order[price &lt; 30]"/>
      </cheapItems>
    </orderSummary>
  </xsl:template>
   
  <xsl:template match="order">
    <xsl:element name="{item}">
      <xsl:attribute name="totalPrice">
        <xsl:value-of select="price * quantity"/>
      </xsl:attribute>
    </xsl:element>
  </xsl:template>
   
</xsl:stylesheet>

This stylesheet introduces some more features of XPath and XSLT. Let’s step through the stylesheet just as we did with the first two examples.

This time, the xsl:output method does not include a method attribute. Since it defaults to xml (as ...

Get Office 2003 XML 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.