Kevin
Kevin

Reputation: 345

xsl:element stored as variable?

Can you store an element name as a variable to be called at a later date?

For example :

<xsl:variable name="element">
            <xsl:choose>
                <xsl:when test="Argument1">strong</xsl:when>
                <xsl:when test="Argument2">em</xsl:when>
            </xsl:choose>
        </xsl:variable>
        <xsl:element name="{$element}">
            <a href="{$url}">
                <xsl:value-of select="title"/>
            </a>
        </xsl:element>

So based on a predefined argument, the element to be wrapped around the anchor tag has either to be <strong> or <em>.

Or am i approaching this wrong?

Going the long way round and duplicating the anchor tag inside a choose when statement for each argument doesn't seem to work.

Thanks, Kevin

Upvotes: 3

Views: 165

Answers (2)

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243529

Your approach is completely valid.

Alternatively, one could use two templates:

<xsl:template match="someElement[Argument1]">
 <strong>
   <a href="{$url}">                 
     <xsl:value-of select="title"/>             
   </a>  
 </strong>
</xsl:template>

<xsl:template match="someElement[Argument2]">
 <em>
   <a href="{$url}">                 
     <xsl:value-of select="title"/>             
   </a>  
 </em>
</xsl:template>

It can be argued that the second approach is more declarative, flexible and maintainable.

Upvotes: 1

Martin Honnen
Martin Honnen

Reputation: 167706

I think your posted sample should work. With XSLT 2.0 you could even do <xsl:element name="{if (Argument1) then 'strong' else if (Argument2) then 'em' else ()}">.

Upvotes: 1

Related Questions