使用 XSLT 2.0 在 table 中查找最长的单元格

Finding the longest cell in a table with XSLT 2.0

基于此主题: How do I select an XML node with the longest child #text node value with XPath? 我尝试在 table 的第 1 列中找到最长的单元格。不幸的是,我不知道 table 有多少个祖先,并且有时在一个文本元素中有几个应该被区别对待。

XML

    <text><table cols="3" rows="2">
        <row >
            <cell >first cell first row</cell>
            <cell >second cell first row
            </cell>
            <cell >third cell first row
                    </cell>
        </row>
        <row >
            <cell >first cell second row</cell>
            <cell >this is an incredible long text</cell>
            <cell />
        </row>
    </table>
</text>

XSLT:

<xsl:stylesheet version="2.0"
   xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

   <xsl:template match="/">
      <xsl:apply-templates/>
   </xsl:template>

     <xsl:template match="table">
         <xsl:variable name="longest1">
         <xsl:sequence select=
            "/*/table/row/cell[1][not(string-length(.) &lt; /*/table/row/cell[1]/string-length(.))]"/>
         </xsl:variable>
<xsl:value-of select="longest1">
</xsl:template>
</xsl:stylesheet>

输出当然应该是"first cell second row",因为第二列没有被处理。 我很确定我所要做的就是修复这一行的 /*:

<xsl:sequence select=
                "/*/table/row/cell[1][not(string-length(.) &lt; /*/table/row/cell[1]/string-length(.))]"/>

但是我看不到解决方案。

在为 table 编写模板时,您可以简单地使用

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xs"
    version="2.0">

    <xsl:template match="table">
        <xsl:sequence select="row/cell[1][not(string-length() &lt; current()/row/cell[1]/string-length())]"/>
    </xsl:template>

</xsl:stylesheet>

当然,另一种方法是简单地按字符串长度对 row/cell[1] 进行排序,然后取最后一个,在 XSLT 3.0 中使用 XPath 3.1 使用 sort(row/cell[1], function($c) { string-length($c)})[last()] 或在 XSLT 2.0 中使用 [=14] =].