2016-09-18 16 views
0

關於此主題的: How do I select an XML node with the longest child #text node value with XPath? 我嘗試查找表格第1列中最長的單元格。不幸的是,我不知道表中有多少祖先,有時在一個文本元素中有幾個應該被區別對待。使用XSLT 2.0查找表中最長的單元格

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> 

當然的輸出應爲 「第一單元第二行」,作爲第2欄是不處理。 我確信我所要做的就是修復/ *此行:

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

但我不能設法看到了解決方案。

回答

1

當你正在寫的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中使用<xsl:variable name="sorted-cells" as="element(cell)*"><xsl:perform-sort select="row/cell[1]"><xsl:sort select="string-length()"/></xsl:perform-sort></xsl:variable><xsl:copy-of select="$sorted-cells[last()]"/>

+0

我不得不求助於與整理您的解決方案,因爲當有相同長度的多細胞的另一種沒有工作:一個一個一個一個將彙編爲AAA。我想它與「低於」有關,應該是「低於或等於」,但這並沒有成功。另一方面,排序工作馬上! – martinanton

+0

您也可以使用'

+0

呵呵,那麼當我在真實生活的工作流程中執行它的時候,我一定會搞砸它,因爲它產生了錯誤。 – martinanton