您可以使用 XSLT 中的函数定义自定义排序规则吗?
我想定义某个元素中使用的字符串的顺序.例如,<class>Senior</class><class>初级</class><class>二年级</class><class>新生<class>将描述课堂上的合理排序.
I'd like to define an ordering on strings used in a certain element. For example, <class>Senior</class> <class>Junior</class> <class>Sophomore</class> <class>Freshman<class> would describe a reasonable ordering on class.
有没有办法使用 <xsl:sort select='class'>会按上面给出的顺序排序吗?
Is there a way using <xsl:sort select='class'> that would sort by the ordering given above?
提前致谢.
您是否研究过 Saxon 的自定义排序规则扩展?
Have you looked into Saxon's custom collation extensions?
例如,
<xsl:variable name="rules" select="'< Freshman < Sophomore
< Junior < Senior'" />
这使用 RuleBasedCollator 格式来自同名的 Java 类.
This uses the RuleBasedCollator format from the Java class of that name.
在您的排序中使用它(捎带在 Tim C 的有用示例输入 XML 和样式表上):
To use it in your sort (piggybacking on Tim C's useful example input XML and stylesheet):
<xsl:apply-templates select="object">
<xsl:sort select="@class"
collation="http://saxon.sf.net/collation?rules={encode-for-uri($rules)}"/>
</xsl:apply-templates>
这给出了与 Tim C 的解决方案相同的结果.(使用 Saxon PE 9.3.0.5 测试.)
This gives the same results as Tim C's solution. (Tested using Saxon PE 9.3.0.5.)
它不是一个 xsl:function,但它比数组提供了更多的灵活性,并且可以说更简洁.AFAICT 无法使用 XSLT 用户定义函数创建自定义排序规则.由于您没有说明为什么需要 xsl:function
,因此很难推测哪些替代方案可以满足您的需求.
It's not an xsl:function, but it gives you a little more flexibility than an array, and is arguably more succinct. AFAICT there is no way to create a custom collation using an XSLT user-defined function. Since you don't say why you want an xsl:function
, it's hard to speculate on what alternatives will meet your needs.
要获得完整的 xsl:function-like 灵活性,您可以在 Java 中定义自己的整理器;参见 http://www.saxonica.com/documentation/extensibility/collation.xml 关于实现 java.util.Comparator 接口并在 class
属性中指定您的比较器.
For complete xsl:function-like flexibility, you could define your own collator in Java; see http://www.saxonica.com/documentation/extensibility/collation.xml on implementing the java.util.Comparator interface and specifying your comparator in the class
attribute.