Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XSLT: can we use abs value?

Tags:

java

xslt

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. I'm using java 1.6 language.

like image 977
CC. Avatar asked Dec 14 '22 00:12

CC.


1 Answers

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

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

This evaluates to abs($x).

Here is a brief demonstration of this in action:

<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="text()">
  <xsl:param name="x" select="."/>
  <xsl:value-of select=
  "($x >= 0)*$x - not($x >= 0)*$x"/>
 </xsl:template>
</xsl:stylesheet>

when this transformation is applied to the following XML document:

<t>
  <num>-3</num>
  <num>0</num>
  <num>5</num>
</t>

the wanted, correct result (abs() on every number) is produced:

<t>
  <num>3</num>
  <num>0</num>
  <num>5</num>
</t>
like image 142
Dimitre Novatchev Avatar answered Jan 01 '23 13:01

Dimitre Novatchev