2

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.

4 Answers 4

5
<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>
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

Try this...

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

Comments

-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.