XSLT: can the abs value be used?

I would like to know if math can be used in XLST: abs (...)? I saw it somewhere, but it didn’t 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 am using java 1.6 language.

+4
source share
5 answers

Here is one XPath expression that implements the abs() function:

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

This evaluates to abs($x) .

Here is a brief demo of this 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 conversion is applied to the following XML document:

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

the desired, correct result (abs () for each number) is created :

 <t> <num>3</num> <num>0</num> <num>5</num> </t> 
+7
source

abs() is trivial enough. Implemented in pure XSLT, it will 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 will call it like this:

 <tag> <xsl:call-template name="abs"> <xsl:with-param name="number" select="number(product/blablaPath)" /> </xsl:call-template> </tag> 
+3
source

Anotherway:

 (2*($x >= 0) - 1)*$x 

When $ x is positive, the test returns "true", so 2 * true-1 returns 1, so the final result is $ x. When $ x is negative, the test returns false, so 2 * false-1 returns -1, so the final result is $ x.

Using

 2*(any-test-here)-1 
is a good way to have +1 when the test is true and -1 when false .
+1
source

A very simple solution is to use the XSL 1.0 translation feature. I.e

 <xsl:value-of select="translate($x, '-', '')/> 
+1
source

math:abs not embedded in XSLT or XPATH. This is the XSLT extension provided by the runtime with which you are converting.

Here is an article about .NET xslt extensions .

Here is one for Java (Xalan).

0
source

Source: https://habr.com/ru/post/1300154/


All Articles