XPath查询返回值为max length的元素

时间:2011-10-24 08:16:53

标签: xml xpath string-length

给出包含文本的元素列表:

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

我正在尝试编写一个XPath 1.0查询,它将返回具有最大文本长度的元素。

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

谢谢。

3 个答案:

答案 0 :(得分:2)

  

我正在尝试编写一个将返回该元素的XPath 1.0查询   最大文本长度

如果事先不知道元素的数量,则不可能编写一个选择元素的XPath 1.0表达式,其字符串长度()是最大值。

在XPath 2.0中,这是微不足道的

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

或其他指定方式,使用常规比较=运算符:

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

答案 1 :(得分:1)

使用纯XPath 1.0无法实现。

答案 2 :(得分: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>

`