Performing a Preorder Traversal
Problem
You want to recursively process an element first and then process its child elements.
Solution
Solutions to this recipe have the following general form:
<xsl:template match="node( )">
<!-- Do something with current node -->
<!--Process children -->
<xsl:apply-templates/>
</xsl:template>Discussion
The term preorder is computer-science jargon for
traversing a tree so you visit the root and recursively visit the
children of the root in preorder. This process is arguably the most
common means of processing XML. Of this idiom’s many
applications, this chapter will consider two. As you review recipes
in later sections, you will see this mode of traversal arise
frequently.
Consider an organization chart (Example 4-2) encoded in a simplistic fashion so that an employee element B is a child of another employee element A if B reports to A. Example 4-16 employs a preorder traversal to explain who manages whom. Example 4-17 shows the output.
Example 4-16. Stylesheet
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text"/> <xsl:strip-space elements="*"/> <xsl:template match="/employee" priority="10"> <xsl:value-of select="@name"/><xsl:text> is the head of the company. </xsl:text> <xsl:call-template name="HeShe"/><xsl:text> manages </xsl:text> <xsl:call-template name="manages"/> <xsl:apply-templates/> </xsl:template> <xsl:template match="employee[employee]"> <xsl:value-of ...
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