與最大長度返回元素給出一個包含文字元素的列表:XPath查詢中值
<root>
<element>text text text ...</element>
<element>text text text ...</element>
<root>
我想寫一個XPath 1.0查詢,將與最大文本長度返回元素。
不幸的是,string-length()返回一個結果而不是一個集合,所以我不知道如何實現它。
謝謝。
與最大長度返回元素給出一個包含文字元素的列表:XPath查詢中值
<root>
<element>text text text ...</element>
<element>text text text ...</element>
<root>
我想寫一個XPath 1.0查詢,將與最大文本長度返回元素。
不幸的是,string-length()返回一個結果而不是一個集合,所以我不知道如何實現它。
謝謝。
使用純XPath 1.0是不可能完成的。
我想寫一個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())]
我知道這是一個老問題,但由於我在尋找內置的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 < $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 > &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>
`