我正在搜索一个与XPath 2.0fn:max函数类似的XPath函数。返回多个参数中的最大值的函数。
在搜索了很多次之后,我想出了这样的方法:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:math="http://exslt.org/math"
xmlns:exslt="http://exslt.org/common"
xmlns:func="http://exslt.org/functions"
xmlns:my="http://myns.com"
extension-element-prefixes="math exslt func">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:template match="/">
<root>
<xsl:value-of select="my:max(1,2)"/>
</root>
</xsl:template>
<func:function name="my:max">
<xsl:param name="e1"/>
<xsl:param name="e2"/>
<xsl:variable name="x">
<val><xsl:value-of select="$e1"/></val>
<val><xsl:value-of select="$e2"/></val>
</xsl:variable>
<func:result select="math:max(exslt:node-set($x)/val)"/>
</func:function>
</xsl:stylesheet>有没有可能让我的max函数可以接受更多的元素?
干杯
1月
发布于 2009-06-11 19:04:59
我面前没有我的XSLT 1.0书籍,但我认为这里的关键是您可以选择“节点集”并将它们设置为参数变量,而不是每个参数一个节点。下面是一个粗略的猜测:
<xsl:template match="/">
<root>
<xsl:call-template name="max">
<xsl:with-param name="values">
<val>1</val>
<val>2</val>
<val>3</val>
</xsl:with-param>
</xsl:call-template>
</root>
</xsl:template>
<func:function name="my:max">
<xsl:param name="x"/>
<func:result select="math:max($x/val/*)"/>
</func:function>
编辑:重新阅读问题和一些XSLT 1.0指南。它应该类似于另一个答案,只是稍微简化了一点。请记住,如果您想要的数字来自XML数据,您可以使用xsl:with-param上的select=属性自动选择您想要比较的节点。
发布于 2009-06-07 22:43:33
假设您可以将xml (用于node-set)指定为输入参数?
我对exslt不感兴趣,但使用了msxsl (仅用于node-set函数,该函数也在exslt中):
<xsl:template name="max">
<xsl:param name="values"/>
<xsl:for-each select="msxsl:node-set($values)/val">
<xsl:sort data-type="number" order="descending"/>
<xsl:if test="position()=1">
<xsl:value-of select="."/>
</xsl:if>
</xsl:for-each>
</xsl:template>
...
<xsl:call-template name="max">
<xsl:with-param name="values">
<val>13</val>
<val>123</val>
<val>18</val>
</xsl:with-param>
</xsl:call-template>发布于 2009-06-12 10:48:59
谢谢你的点子。
你帮我更好地理解了一切。但我的初衷是获得一个处理xsl变量的方便的XPath函数。
<!-- works with XPath 2.0 -->
<xst:template match="img/@height">
<xsl:variable name="$maximageheight" select="200">
<xsl:value-of select="fn:max( $maximageheight , . )"/>
</xsl:template>
<!-- until now the only way I see to do the same in XSL 1.0 -->
<xst:template match="img/@height">
<xsl:variable name="$maximageheight" select="200">
<xsl:call-template name="max">
<xsl:with-param name="values">
<val>$maximageheight</val>
<val><xsl:value-of select="."/></val>
</xsl:with-param>
</xsl:call-template>
</xsl:template>对于固定数量的参数,可以实现exslt函数:
<func:function name="my:max" xmlns:func="http://exslt.org/functions">
<xsl:param name="e1"/>
<xsl:param name="e2"/>
<xsl:variable name="x">
<val><xsl:value-of select="$e1"/></val>
<val><xsl:value-of select="$e2"/></val>
</xsl:variable>
<func:result select="math:max(exslt:node-set($x)/val)"/>
</func:function>但我看不到一种方法来实现它或可变数量的参数。
https://stackoverflow.com/questions/962951
复制相似问题