[Previous] [Contents] [Next]


Matching an Element by its Attributes


The syntax for matching by an attribute is

<xsl:template match="element-name[@attribute-name="attribute-value"]">

Consider the XML document shown in Listing 20.5.

Listing 20.5 A Simple XML File with Attributes


1: <chapter>
2:   <section number="1">
3:     <title>first</title>
4:     <para type="first">Some text</para>
5:     <para>Some <em>emphasized</em> text</para>
6:     <para>Another para with no attributes</para>
7:     <para type="last">Some more text</para>
8:   </section>
9:
10:   <section number="2">
11:     <title>two</title>
12:     <para type="first">Some text</para>
13:     <para>Some <em>emphasized</em> text</para>
14:     <para>Another para with no attributes</para>
15:     <para type="last">Some more text</para>
16:   </section>
17: </chapter>

The following examples demonstrate how you can use the attributes and their values to select elements from the XML file shown in Listing 20.5:

<xsl:template match="para">-Matches all the para elements (with and without attributes).
<xsl:template match="para[@type)]">-Matches all the para elements that have a type attribute (the value of the attribute doesn't matter).
<xsl:template match="para[@type='first']">-Matches all the para elements that have a type attribute with a value of "first".
<xsl:template match="section[@number= '1']/para[@type='first']">-Matches all the para elements with a type attribute whose value is "first", and that have a parent of section with a number attribute with a value of 1 (the very first para element in Listing 20.5).

[Previous] [Contents] [Next]