views:

37

answers:

3

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

+3  A: 

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 &lt; 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>
jabley
select cannot be in xsl:attribute
liysd
+1  A: 

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.

Alejandro
+4  A: 

This transformation:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"&gt;
 <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.

Dimitre Novatchev
+1 Better and compact expression with numbers intead of strings
Alejandro
@Dimitre: Off topic. `xquery` questions are growing. Maybe you would like to revisit them.
Alejandro
Is it possible to find orginal size of image without extra parameter (orginal size). I mean always display image in its normal size except when its greater than max?
liysd
@liysd: Original size isn't parameter here. max is. If you don't want to use a parameter at all, you can hardcode it -- just change `<xsl:param>` to `<xsl:variable>`
Dimitre Novatchev