Search code examples
xsltxpathaxes

Axes in XSLT template match


I want a template match like this:

<xsl:template match="//content[parent::(@type='async')]">
 <table>
  <thead>
   <xsl:apply-templates select="row[@type='header']" />
  </thead>
  <tbody>
   <xsl:apply-templates select="/row[@type='data']" />
  </tbody>
 </table>
</xsl:template>

With this XML:

<document type="async">
 <content>
  <!-- Some rows with types -->
 </content>
</document>

My problem is the <xsl:template match="//content[parent::(@type='async')]">, how do I make this work?


Solution

  • Here's one way:

    //content[parent::*/@type='async']
    

    which can be shortened to:

    //content[../@type='async']
    

    Here's another:

    //*[@type='async']/content
    

    Note:
    In general, it's always best to be explicit and avoid the * notation if you know the element's name (document in this case), and particularly the // symbol if you know the exact path.

    Specifically, in a match pattern a leading // is redundant because a template will be automatically applied if (and only if) the pattern is matched in the course of traversing the input tree.