gpt4 book ai didi

xml - 如何xsl最后用空值升序排序

转载 作者:数据小太阳 更新时间:2023-10-29 02:05:52 24 4
gpt4 key购买 nike

我想按升序对这些元素进行排序,但空值排在最后而不是排在前面,这似乎是 xslt 默认情况下所做的。我设法做到了这一点,但想知道是否有更好的方法。这是我的例子。

<b>
<c>2</c>
<c>1</c>
<c>3</c>
<c></c>
<c>15</c>
<c>11</c>
<c></c>
<c>43</c>
<c>4</c>
</b>


<xsl:template match="/">
<xsl:for-each select="b/c">
<xsl:sort select="node() = false()"/>
<xsl:sort select="." data-type="number"/>
Row<xsl:value-of select="position()"/>:<xsl:value-of select="."/>
</xsl:for-each>
</xsl:template>

它给出了所需的输出:

Row1:1
Row2:2
Row3:3
Row4:4
Row5:11
Row6:15
Row7:43
Row8:
Row9:

我目前正在使用 <xsl:sort select="node() = false()"/>测试它是否为 null 然后使用排序对 null 元素最后排序(null 将为 1 而不是 null 将为 0 因此它正确排序它们)。

谁能提出比这更好的建议?

最佳答案

<xsl:template match="/">
<xsl:for-each select="b/c">
<xsl:sort select="concat(
substring('1', 1, boolean(text())),
substring('0', 1, not(boolean(text())))
)" />
<xsl:sort select="." data-type="number"/>
<xsl:text>Row</xsl:text>
<xsl:value-of select="position()"/>
<xsl:text>:</xsl:text>
<xsl:value-of select="."/>
<xsl:text>&#10;</xsl:text>
</xsl:for-each>
</xsl:template>

这个:

concat(
substring('1', 1, boolean(text()) ),
substring('0', 1, not(boolean(text())))
)

生成“0”或“1”,具体取决于是否有子文本节点。它是两个互斥字符串的串联 - XPath 1.0 中的穷人的 if/then/else。

boolean(text()) 生成 truefalse,然后将其转换为数字以供 substring() 。 bool 值分别转换为 1 或 0。

上面的更完整的版本是这样的:

concat(
substring(
$if_str,
1,
boolean($condition) * string-length($if_str)
),
substring(
$else_str,
1,
not(boolean($condition)) * string-length($else_str)
)
)

关于xml - 如何xsl最后用空值升序排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1538542/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com