How to select first node only in xslt

apply-templatesxslt

My XML provides me with multiple images assigned to different 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 the 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 the thumbnail from the first mmid (in this case 22404). I have NO control over the mmid value.

How do I stop my template so it only outputs the thumb file of the first mmid?

Many thanks for any help!

Best Answer

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

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

The [@mmid] constrains the selection to child Mediendaten elements that carry the mmid attribute, the [1] constrains the selection to the first one of these.

P.S. Whoever designed the XML you are using hates you. (Using the same name for both kinds of element now labeled Mediendaten is a dirty rotten trick; it makes everything you do with the data harder. Try to figure out what you did to piss them off so badly, and make amends to them. Just a word to the wise.)

Related Topic