2011-10-24 86 views
0

与最大长度返回元素给出一个包含文字元素的列表:XPath查询中值

<root> 
    <element>text text text ...</element> 
    <element>text text text ...</element> 
<root> 

我想写一个XPath 1.0查询,将与最大文本长度返回元素。

不幸的是,string-length()返回一个结果而不是一个集合,所以我不知道如何实现它。

谢谢。

回答

1

使用纯XPath 1.0是不可能完成的。

2

我想写一个XPath 1.0查询,将与最大文本长度

如果元素的数量是事先不知道返回元素 ,这是不可能的编写一个XPath 1.0表达式来选择元素,其string-length()是最大值。

在XPath 2.0,这是微不足道的

/*/element[string-length() eq max(/*/element/string-length())] 

或指定此,使用一般比较=运营商的另一种方式:

/*/element[string-length() = max(/*/element/string-length())] 
0

我知道这是一个老问题,但由于我在寻找内置的XPath 1.0解决方案时发现了它,也许我的建议可能会为其他人提供帮助,同样也在寻找最大长度的解决方案。

如果需要在XSLT样式表的最大长度值,该值可以与模板中找到:

<!-- global variable for cases when target nodes in different parents. --> 
<xsl:variable name="ellist" select="/root/element" /> 
<!-- global variable to avoid repeating the count for each iteration. --> 
<xsl:variable name="elstop" select="count($ellist)+1" /> 

<xsl:template name="get_max_element"> 
    <xsl:param name="index" select="1" /> 
    <xsl:param name="max" select="0" /> 
    <xsl:choose> 
     <xsl:when test="$index &lt; $elstop"> 
     <xsl:variable name="clen" select="string-length(.)" /> 
     <xsl:call-template name="get_max_element"> 
      <xsl:with-param name="index" select="($index)+1" /> 
      <xsl:with-param name="max"> 
       <xsl:choose> 
        <xsl:when test="$clen &gt; &max"> 
        <xsl:value-of select="$clen" /> 
        </xsl:when> 
        <xsl:otherwise> 
        <xsl:value-of select="$max" /> 
        </xsl:otherwise> 
       </xsl:choose> 
      </xsl:with-param> 
     </xsl:call-template> 
     </xsl:when> 
     <xsl:otherwise><xsl:value-of select="$max" /></xsl:otherwise> 
    </xsl:choose> 
</xsl:template> 

`