tags:

views:

256

answers:

3

Hi guys,

I would like to know if in XLST can we use the math:abs(...) ? I saw this somewhere but it does not work . I have something like:

<tag>
  <xsl:value-of select="./product/blablaPath"/>
</tag>

I tried to do something like:

<tag>
  <xsl:value-of select="math:abs(./product/blablaPath)"/>
</tag>

but does not work.

Any ideas? Thanks.

Corneliu.

A: 

math:abs is not built in to XSLT or XPATH. It is an XSLT extension, provided by the runtime you are transforming with.

Here is an article about .NET xslt extensions.

Here is one for Java (Xalan).

Oded
I would prefer to modify only the xslt file not the java code, because there is alot of impact in java code.
CC
Too bad. `math:abs` would be provided as an xslt extension by your java code. Read the linked articles to see how this is exposed to your xslt.
Oded
+2  A: 

abs() is trivial enough. Implemented in pure XSLT it would look like this:

<xsl:template name="abs">
  <xsl:param name="number">

  <xsl:choose>
    <xsl:when test="$number &gt;= 0">
      <xsl:value-of select="$number" />
    <xsl:when>
    <xsl:otherwise>
      <xsl:value-of select="$number * -1" />
    </xsl:otherwise>
  </xsl:if>
</xsl:template>

in your context you would invoke it like this:

<tag>
  <xsl:call-template name="abs">
    <xsl:with-param name="number" select="number(product/blablaPath)" />
  </xsl:call-template>
</tag>
Tomalak
Actually, I found the solution.There allready a math:abs implemented.I just used <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:math="xalan://java.lang.Math" extension-element-prefixes="math">and for my noedI've put "math:abs(...)"
CC
My solution was targeted at XSLT 1.0 since that you did not mention that you could use version 2.0.
Tomalak
See a one-liner solution I just added :)
Dimitre Novatchev
+1  A: 

Here is a single XPath expression implementing the abs() function:

($x >= 0)*$x - not($x >= 0)*$x

This evaluates to abs($x).

Dimitre Novatchev
Basically this resembles what I know as "Becker's Method", only that he did it with strings. :) +1
Tomalak
@tomalak Actually, this is just 1:1 the definition of abs().If $x >= 0, then just $x (multiplied by 1),If $x < 0, then $x multiplied by -1THe conditions above are mutually exclusive, so exactly one of them is true (1) and exactly one is false (0).We use this to sum the two and produce a single formula.
Dimitre Novatchev
@Dimitre: That's exactly what is called "Becker's Method" when done with strings. :) See Олэг's blog: http://www.tkachenko.com/blog/archives/000156.html.
Tomalak
@tomalak This is a property of XPath 1.0's coersion of boolean into number. It has been used extensively and not only by O.B.
Dimitre Novatchev