tags:

views:

96

answers:

4

I have a repeating xml tree like this -

<xml>
  <head>this is a sample xml file</head>
  <item><color>yellow</color><color>red</color></item>
  <item><color>blue</color></item>
  <item><color>grey</color><color>red</color><color>blue</color></item>
</xml>

As you can see, each item can have a varying number of color tags.

I wish to get all the color tags for the first two items only.

A: 

Add an ordinal field to each item and select the first two.

Dave Swersky
+4  A: 
<xsl:template match="xml">
  <xsl:apply-templates select="item[position() &lt; 3]/color" />
</xsl:template>

<xsl:template match="color">
  <xsl:copy-of select="." />
</xsl:template>

Applied to your XML this yields:

<color>yellow</color>
<color>red</color>
<color>blue</color>
Tomalak
A: 

One potential possible way to get the items which is technically perfectly correct and in no way makes assumptions about the structure of your document with respect to namespacing, future requirements or template construction is just a simple:

/xml/item[position() &lt; 3]/color
annakata
A: 

Try this...

/xml/item[ position() &lt; 3 ]/color
David