xsl-list
[Top] [All Lists]

Re: Selecting only one element using templates

2003-12-01 06:35:52
Basically my XML data structure allows elements to contain data or other
elements, like so:

<fruits>
    <fruit>apple</fruit>
    <fruit>banana</fruit>
    <fruit>
        <fruit>pear</fruit>
        <color>green</fruit>
    </fruit>
    <fruit>
        <fruit>orange</fruit>
        <color>orange</color>
    </fruit>
</fruits>

This structure is slightly confusing; you have two 'fruit' nodes which mean 
different things.

Consider the following:

<fruit>
   <name>apple</name>
</fruit>
<fruit>
   <name>pear</name>
   <color>green</color>
</fruit>

or:

<fruit>apple</fruit>
<fruit color="green">pear</fruit>

which are probably a bit clearer.

I just wanted to select the fruit name using templates, but if I did this:

<xsl:templates match="fruit">

I get all fruit nodes(term?) and also the colors as well. So my output was:

apple
banana

pear
green

orange
orange

If you have an <xsl:apply-templates /> element in a <xsl:template match="..."> 
element then the child nodes will be processed as well.

If you want elements to be left out you can define empty templates for them:

<xsl:template match="color" />

Or if you use the second of the modified XML structures above you can use

<xsl:template match="fruit">

where the context will be the name of the fruit and @color will be its colour.

(You may also want to look at the <xsl:for-each> element.)

Cheers,
Richard


 XSL-List info and archive:  http://www.mulberrytech.com/xsl/xsl-list