How can we create attributes based on some condition in xslt.
My input xml has a tag:
<track external="http://mysite.com" />
or
<track local="/myfolder" />
and in this ‘track element either external or local attribute appears but not either of these and i have to convert it into
<a xhtml:href="@external value" xmlns="http://www.w3.org/1999/xhtml" />
if ‘extrenal’ attribute occurs for ‘track’ element or into
<a xlink:href="@local value" xmlns="http://www.w3.org/1999/xlink" />
if ‘local’attribute occurs for ‘track’ element
XSLT tried:
<a xmlns:xhtml="http://www.w3.org/1999/xhtml" xmlns:xlink="http://www.w3.org/1999/xlink">
<xsl:for-each select="child::*" >
<xsl:choose>
<xsl:when test="name()='track'">
<xsl:if test="@local">
<xsl:attribute name="xlink:href">
<xsl:value-of select="@local" />
</xsl:attribute>
</xsl:if>
<xsl:if test="@external">
<xsl:attribute name="xhtml:href">
<xsl:value-of select="@external" />
</xsl:attribute>
</xsl:if>
</xsl:when>
</xsl:choose>
</xsl:for-each>
</a>
but exception is thrown as i created attributes for ‘a’ element based on a condition. This is not accepted in XSLT 1.0, is there any way to make attribute appear for my ‘a’ element based on some condition in XSLT 1.0.
There is nothing preventing you conditionally adding attributes in XSLT 1.0. Incidentally, avoid for-each in XSLT and use templates instead. Here’s a dedicated template for
tracknodes.As Tim C mentioned, though, a better pattern would be to handle the different types of incoming attribute via different templates. As much as anything, this is cleaner, as you don’t get bogged down in conditional blocks.
You can see both approaches in action in this XMLPlayground.