7

Is there any one line if condition in xslt such as suppose i want to add attributes only based on some condition

e.g.

<name (conditionTrue then defineAttribute)/>

just to avoid if

<xsl:if test="true">
   <name defineAttribute/>
</xsl:if>
0

2 Answers 2

12

You can use <xsl:element> to create the output element and <xsl:attribute> for its attributes. Then adding conditional attributes is simple:

<xsl:element name="name">
  <xsl:if test="condition">
     <xsl:attribute name="myattribute">somevalue</xsl:attribute>
  </xsl:if>
</xsl:element>
1
  • 3
    I'd like to mention that you have to do this immediately after opening the element. You can't do other stuff first.
    – DanMan
    Commented Aug 14, 2014 at 14:52
8

Here is one example how to avoid completely the need to specify <xsl:if>:

Let's have this XML document:

<a x="2">
 <b/>
</a>

and we want to add to b an attribute parentEven="true" only in the case when the value of the x attribute of b's parent is an even number.

Here is how to do this without any explicit conditional instructions:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <xsl:template match="node()|@*">
     <xsl:copy>
       <xsl:apply-templates select="node()|@*"/>
     </xsl:copy>
 </xsl:template>

 <xsl:template match="a[@x mod 2 = 0]/b">
  <b parentEven="true">
   <xsl:apply-templates select="node()|@*"/>
  </b>
 </xsl:template>
</xsl:stylesheet>

When this transformation is applied on the XML document above, the wanted, correct result is produced:

<a x="2">
   <b parentEven="true"/>
</a>

Do note:

Using templates and pattern matching one can eliminate completely the need to specify explicit conditional instructions. The presence of explicit conditional instructions in the XSLT code should be considered a "code smell" and should be avoided as much as possible.

0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.