[英]XSLT: can we use abs value?
I would like to know if in XLST can we use the math:abs(...) ? 我想知道在XLST中我们是否可以使用数学: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. 我正在使用java 1.6语言。
Here is a single XPath expression implementing the abs()
function: 这是一个实现abs()
函数的XPath表达式 :
($x >= 0)*$x - not($x >= 0)*$x
This evaluates to abs($x)
. 这评估为 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: 当此转换应用于以下XML文档时:
<t>
<num>-3</num>
<num>0</num>
<num>5</num>
</t>
the wanted, correct result (abs() on every number) is produced : 在想,正确的结果 (ABS()上的每个数字) 产生 :
<t>
<num>3</num>
<num>0</num>
<num>5</num>
</t>
abs()
is trivial enough. abs()
是微不足道的。 Implemented in pure XSLT it would look like this: 在纯XSLT中实现它看起来像这样:
<xsl:template name="abs">
<xsl:param name="number">
<xsl:choose>
<xsl:when test="$number >= 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>
Anotherway: 其他方式:
(2*($x >= 0) - 1)*$x
When $x is positive, the test returns "true", so 2*true-1 returns 1, so final result is $x. 当$ x为正数时,测试返回“true”,因此2 * true-1返回1,因此最终结果为$ x。 When $x is negative, the test returns "false", so 2*false-1 returns -1, so final result is -$x. 当$ x为负数时,测试返回“false”,因此2 * false-1返回-1,因此最终结果为 - $ x。
Using 运用
2*(any-test-here)-1
is a good way to have +1 when test is true , and -1 when false .
是有+1时,测试结果为真时-1 假的好方法,而且。
A very simple solution is to use the XSL 1.0 translate function. 一个非常简单的解决方案是使用XSL 1.0转换功能。 Ie 即
<xsl:value-of select="translate($x, '-', '')/>
math:abs
is not built in to XSLT or XPATH. math:abs
不是内置于XSLT或XPATH中。 It is an XSLT extension, provided by the runtime you are transforming with. 它是一个XSLT扩展,由您正在转换的运行时提供。
Here is an article about .NET xslt extensions . 这是一篇关于.NET xslt扩展的文章。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.