Frage

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.

War es hilfreich?

Lösung

It is impossible to accomplish using pure XPath 1.0.

Andere Tipps

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())]

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>

`

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top