RE: [xsl] Using attributes with XPath

Subject: RE: [xsl] Using attributes with XPath
From: Wendell Piez <wapiez@xxxxxxxxxxxxxxxx>
Date: Thu, 24 Aug 2006 12:17:35 -0400
Mike,

How about simply

<xsl:template match="list/@type">
  ... cool code ...
</xsl:template>

which is more concise and easier to maintain than either a distinct mode, or name-testing on the parent (which shouldn't require passing a parameter in any case)?

More generally, I think problems like Jacqueline's are usually dealt with most simply at the level of the list, where the "natural" mapping to the result element will be:

<xsl:template match="list">
  do stuff for lists
</xsl:template>

<xsl:template match="list[@type='special']">
  do stuff for special lists
</xsl:template>

Because of the template matching rules, the second template will apply when it can, and the first will apply when the second one can't.

Note that when you've matched an attribute, <xsl:apply-templates/> won't get you the contents of the element since they're not inside the attribute. So matching attributes is most common when we're just adding a bit of generated text or some such.

Cheers,
Wendell

At 01:07 AM 8/24/2006, you wrote:
Jackie,
If you want to write templates for common attributes, you can
distinguish them in two ways (XSLT 1.0).

1. use the mode attributes in the xsl:apply-templates and
xsl:template. This will single out the attribute for particular
transformation for each instance. In your case it would mean a
template for the list/@type attribute and one for each other
instance. You will need to think of your tranformation in catagories
(common transformation vs. uncommon). Use a general template for the
common, and particular templates for what is not common.

<xsl:apply-templates select="@type" mode="list_parent"/>

<xsl:template match="@type" mode="list_parent">
<!-- your cool code here for a list/@type transformation -->
</xsl:template>

2. You can get fancy by using a param and a single template for a
common attribute.

<xsl:apply-templates select="@type">
  <xsl:with-param name="parent_x" select="local-name()"/>
</xsl:apply-templates>

<xsl:template match="@type">
  <xsl:param name="parent_x"/>
  <xsl:choose>
    <xsl:when test="string($parent_x)='list'">
<!-- cool code here for list/@type -->
    </xsl:when>
    <xsl:otherwise>
<!-- cool code here for all the rest -->
    </xsl:otherwise>
  </xsl:choose>
</xsl:template>

Current Thread