the-lights
the-lights

Reputation: 153

XPath query to return the element with the max length in value

Given a list of elements containing text:

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

I'm trying to write an XPath 1.0 query that will return the element with the max text length.

Unfortunately string-length() returns a single result and not a set, so I'm not sure how to accomplish it.

Thank you.

Upvotes: 0

Views: 4082

Answers (3)

chuckj
chuckj

Reputation: 155

I know it's an old question, but since I found it while looking for a built-in XPath 1.0 solution, perhaps my suggestion might serve someone else, likewise looking for a max-length solution.

If the max length value is needed in an XSLT stylesheet, the value can be found with a template:

<!-- 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>

`

Upvotes: 0

Dimitre Novatchev
Dimitre Novatchev

Reputation: 243529

I'm trying to write an XPath 1.0 query that will return the element with the max text length

If the number of elements isn't known in advance, it isn't possible to write a single XPath 1.0 expression that selects the element, whose string-length() is the maximum.

In XPath 2.0 this is trivial:

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

or another way of specifying this, using the general comparison = operator:

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

Upvotes: 3

Kirill Polishchuk
Kirill Polishchuk

Reputation: 56182

It is impossible to accomplish using pure XPath 1.0.

Upvotes: 1

Related Questions