0

给定一个包含文本的元素列表:

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

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

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

谢谢你。

4

3 回答 3

3

我正在尝试编写一个 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())]
于 2011-10-24T13:19:31.567 回答
1

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

于 2011-10-24T10:40:09.710 回答
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>

`

于 2018-01-12T15:36:52.820 回答