I can't think of a simple and elegant way to find "previous" and "next" elements in an XML document using XPath or a simple XSLT template. Here's a sample XML document (in a real document, the @id
's wouldn't be ordered so simply)
<manual>
<section id="1">
<section id="2">
<section id="3"/>
<section id="4"/>
<section id="5"/>
</section>
<section id="6">
<section id="7"/>
<section id="8"/>
<section id="9"/>
</section>
</section>
<section id="10"/>
<section id="11">
<section id="12"/>
</section>
</manual>
And here's what I mean by previous / subsequent in document order
+------------------+------------------+--------------+
| Selected section | Previous section | Next section |
+------------------+------------------+--------------+
| 1 | none | 2 |
| 2 | 1 | 3 |
| 3 | 2 | 4 |
| 4 | 3 | 5 |
| 5 | 4 | 6 |
| ... | ... | ... |
| 10 | 9 | 11 |
| 11 | 10 | 12 |
| 12 | 11 | none |
+------------------+------------------+--------------+
The problem with the preceding::
axis is that ancestors are excluded, i.e. section[id=2]
is not a preceding node of section[id=3]
.
In the same way, the following::
axis excludes descendants, i.e. section[id=3]
is not a following node for section[id=2]
.
So how could I produce "previous" and "next" elements e.g. from these templates:
<xsl:template match="section" mode="prev">
<xsl:value-of select="... what to put here ..."/>
</xsl:template>
<xsl:template match="section" mode="next">
<xsl:value-of select="... what to put here ..."/>
</xsl:template>
Note, this is a similar but not the same question here: XPath 1.0 closest preceding and/or ancestor node with an attribute in a XML Tree. These XPath constructions are really over my head, sometimes...
preceding:: and ancestor::
? That won't work for@id=6
, where the previous section should be 5, I think? – Lukas Eder