xsl:apply-imports

1. Match on attribute anywhere, using apply-imports

1.

Match on attribute anywhere, using apply-imports

Jeni Tennison



>  if you have several templates and the knowledge that @mark
> could appear on any element, it wouldnt be so easy. It would be
> great to add just one extra template to match @mark anywhere, and
> highlight its contents.

Actually, this is a situation xsl:apply-imports can actually be useful!

Have your general templates, each dealing with individual nodes in one stylesheet (I'll call it base.xsl).

Then create another stylesheet that *imports* that base stylesheet:

<xsl:stylesheet version="1.0"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:import href="base.xsl" />

...

</xsl:stylesheet>

Within that stylesheet, create a template that matches elements with mark attributes, which creates the span element that you're after:

<xsl:template match="*[@mark]">
  <span style="color:#FF0000">
    ...
  </span>
</xsl:template>

For the content of the span element, you want to use the template in the base.xsl stylesheet for whatever element it is has been matched by this template. This is exactly what the xsl:apply-imports instruction allows you to do. If you add:

<xsl:template match="*[@mark]">
  <span style="color:#FF0000">
    <xsl:apply-imports />
  </span>
</xsl:template>

The processor will take the current node (the element with the mark attribute) and look in the imported stylesheets (just base.xsl in this example) for a template that matches that node. The result of that template becomes the content of the span element.

If an element doesn't have a mark attribute, then the processor just uses the imported template anyway.