Displaying element's ancestors

If you need to process the whole path from the root element to the current element, the ancestor:: axis provides a convenient means of doing that, more so as it lists elements from the root element toward the current one (the opposite direction from what you'd get with the parent:: axis). For example, assume you have an online book with the following structure:
<book title="Sample book">
  <chapter title="First chapter">
    <section title="Section in first chapter">
      <section title="Chunk of text within a section">
        <para>My paragraph</para>
      </section>
    </section>
  </chapter>
</book>

The section elements can be nested

You could use the following template to display the breadcrumbs in front of each heading:

<xsl:template match="chapter|section">
  <p class='crumbs'>

Walk through all the ancestors, starting from the root element

    <xsl:for-each select="ancestor::*">

If the current element has an ancestor, we've obviously printed something already, so insert a breadcrumb separator …

      <xsl:if test="ancestor::*"><xsl:text>, </xsl:text></xsl:if>

… and display the title of the ancestor element.

      <xsl:value-of select="@title" />
    </xsl:for-each>
  </p>

At the end, display the current heading and recursively process child elements.

  <h2><xsl:value-of select="@title" /></h2>
  <xsl:apply-templates />
</xsl:template>

No comments:

Post a Comment