[xsl] learned a lesson about XPath variable evaluations sorting in document order

Subject: [xsl] learned a lesson about XPath variable evaluations sorting in document order
From: "Chris Papademetrious christopher.papademetrious@xxxxxxxxxxxx" <xsl-list-service@xxxxxxxxxxxxxxxxxxxxxx>
Date: Thu, 16 Feb 2023 23:34:01 -0000
Hi everyone,

Given the following input:

<?xml version="1.0" encoding="utf-8" ?>
<root>
  <data>1</data>
  <group>
    <data>2</data>
    <group>
      <data>3</data>
      <results>
        <!-- put ancestor <data> values here, closest first -->
      </results>
    </group>
  </group>
</root>

I wanted the lowest-level <results> element to contain all the ancestor <data>
values, in order of closest ancestor first. By applying reverse() to the
ancestor results, this gives the desired results of "321":

  <xsl:template match="results">  <!-- summarize <data> -->
    <xsl:variable name="all-data" as="text()*"
select="reverse(ancestor::*/data/text())"/>
    <xsl:copy>
      <xsl:value-of select="$all-data"/>
    </xsl:copy>
  </xsl:template>

But if I move the text() evaluation from the <xsl:variable> to the
<xsl:value-of>, then I get "123" instead:

  <xsl:template match="results">  <!-- summarize <data> -->
    <xsl:variable name="all-data" as="element()*"
select="reverse(ancestor::*/data)"/>
    <xsl:copy>
      <xsl:value-of select="$all-data/text()"/>
    </xsl:copy>
  </xsl:template>

The cause is that the "/" in "$all-data/text()" XPath expression causes the
results to be sorted in document order. Somehow I thought that once the
elements were in the variable, they became disassociated with the source
document. But apparently they're not, which updates my mental model.

If I change "/" to the "!" operator (apply an operation to each item in a
sequence), then I get "321" again because the reversed ancestor order is
preserved:

      <xsl:value-of select="$all-data ! text()"/>

Anyway, just passing this along as a friendly reminder to the other novices on
the list. I spent more time than I'd like to admit figuring this out on my
more complicated stylesheet.


  *   Chris

P.S. MANY thanks to Martin for enabling me to fiddle my way to understanding!

-----
Chris Papademetrious
Tech Writer, Implementation Group
(610) 628-9718 home office
(570) 460-6078 cell

Current Thread