I have a XML that contains img tag
<xml>
<img src="/path/to/file.jpg" orginalwidth="150" />
</xml>
I want to have:
<img src="/paht/to/file.jpg" size=SIZE />
Where SIZE is minimum of orginalsize and 100px
I have a XML that contains img tag
<xml>
<img src="/path/to/file.jpg" orginalwidth="150" />
</xml>
I want to have:
<img src="/paht/to/file.jpg" size=SIZE />
Where SIZE is minimum of orginalsize and 100px
Using XSLT 1.0 (XSLT 2.0 probably gives you other options, but not sure if you are in a position to use it):
<img src="{@src}">
<xsl:choose>
<xsl:when test="@originalsize < 100">
<xsl:attribute name="size"><xsl:value-of select="@originalsize"/></xsl:attribute>
<xsl:otherwise>
<xsl:attribute name="size">100</xsl:attribute>
</xsl:otherwise>
</xsl:choose>
</img>
Whenever is posible to use literal result elements an attributes value templaes, do use it.
<img src="{@src}" size="{substring('100',
1 div (@orginalwidth > 100))
}{substring(@orginalwidth,
1 div not(@orginalwidth > 100))
}px"/>
EDIT: Minimum not maximum, sorry.
This transformation:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:param name="pmaxSize" select="100"/>
<xsl:template match="node()|@*">
<xsl:copy>
<xsl:apply-templates select="node()|@*"/>
</xsl:copy>
</xsl:template>
<xsl:template match="@orginalwidth">
<xsl:attribute name="size">
<xsl:value-of select=".*not(. > $pmaxSize) + $pmaxSize*(. > $pmaxSize)"/>
<xsl:text>px</xsl:text>
</xsl:attribute>
</xsl:template>
</xsl:stylesheet>
when performed on the provided XML document:
<xml>
<img src="/path/to/file.jpg" orginalwidth="150" />
</xml>
produces the wanted result:
<xml>
<img src="/path/to/file.jpg" size="100px"/>
</xml>
when applied on the following XML document:
<xml>
<img src="/path/to/file.jpg" orginalwidth="99" />
</xml>
the result is again the wanted and correct one:
<xml>
<img src="/path/to/file.jpg" size="99px"/>
</xml>
Explanation:
In XPath 1.0 any boolean value, when used as a number is converted from true()
to 1
and from false()
to 0
.
Therefore, the expression:
.*not(. > $pmaxSize) + $pmaxSize*(. > $pmaxSize)
evaluates to .
if .
is less or equal $pmaxSize
and to $pmaxSize
otherwize.
.
is the value of the current node interpreted as number.