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>
You can use <xsl:element> to create the output element and <xsl:attribute> for its attributes. Then adding conditional attributes is simple: Show activity on this post. Here is one example how to avoid completely the need to specify <xsl:if>:
The xsl:attribute element is used to add an attribute value to an xsl:element element or literal result element, or to an element created using xsl:copy. The attribute must be output immediately after the element, with no intervening character data.
Permitted parent elements: xsl:attribute-set; any XSLT element whose content model is sequence-constructor; any literal result element Attribute name, interpreted as an attribute value template, so it may contain string expressions within curly braces.
Note: The <xsl:attribute> element replaces existing attributes with equivalent names. <!-- Content:template --> Required. Specifies the name of the attribute
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With