How to select the first node only in xslt

My XML provides me with several images assigned to various mmids:

<Mediendaten> <Mediendaten mmid="22404"> <url size="original">A 22404 FILE</url> <url size="thumb">ANOTHER 22404 FILE</url> </Mediendaten> <Mediendaten mmid="22405"> <url size="original">A 22405 FILE</url> <url size="thumb">ANOTHER 22405 FILE</url> </Mediendaten> <Mediendaten> 

My XSLT selects only URLs where size = thumb:

 <xsl:template match="/Mediendaten"> <xsl:apply-templates select="Mediendaten/url"> </xsl:apply-templates> </xsl:template> <xsl:template match="Mediendaten/url"> <xsl:if test="@size = 'thumb'"> <img width="280" border="0" align="left"> <xsl:attribute name="src"><xsl:value-of select="."/></xsl:attribute> </img> </xsl:if> </xsl:template> 

HOWEVER, I only need a thumbnail from the first mmid (in this case 22404). I have no control over the mmid value.

How to stop my template so that it only displays the thumb file of the first mmid?

Thanks so much for any help!

+7
source share
3 answers

The easiest way is to change the template for /Mediendaten :

 <xsl:template match="/Mediendaten"> <xsl:apply-templates select="Mediendaten[@mmid][1]/url"/> </xsl:template> 

[@mmid] constrains the selection for Mediendaten child elements that carry the mmid attribute, [1] limits the selection to the first of them.

PS The person who designed the XML you use hates you. (Using the same name for both types of items marked as Mediendaten is a dirty rotten trick, it makes everything you do with the data harder. Try to figure out what you did to make them very angry and make corrections Just the word wise.)

+11
source
 <xsl:apply-templates select="Mediendaten[1]/url" /> 
+1
source

Somme welcomes.

First of all, follow the suggestion of Mads Hansen. You have a template that now, how to handle "large" images.

 <xsl:template match="Mediendaten/url[@size = 'thumb']" > <img width="280" border="0" align="left" src="{.}" /> </xsl:template> 

Then, if you want to display only the first image with the stroke (from the Mediendaten document in ), use:

 <xsl:template match="/Mediendaten"> <xsl:apply-templates select="Mediendaten[1]/url[@size = 'thumb']" /> </xsl:template> 

But if the value is “HOWEVER, I only need a thumbnail from the first mmid” is not Mediendaten (with mmid) in document order, but from Mediendaten with the smallest mmid. Try the following:

 <xsl:template match="/Mediendaten"> <xsl:for-each select="Mediendaten"> <xsl:sort select="@mmid"/> <xsl:if test="position()=1"> <xsl:apply-templates select="url[@size = 'thumb']" /> </xsl:if> </xsl:for-each> </xsl:template> 
0
source

All Articles