Get text between two self-closing elements and number of following/preceding element

117 views Asked by At
<text>
    <pb n="I"/>
    <p>
        <lb/>Lorem ipsum
        <lb/>Lorem ipsum
        <lb/>Lorem ipsum
        <pb n="II"/>
        <lb/>Lorem gipsum
        <lb/>Lorem gipsum
    </p>
    <p>
        <lb/>Lorem gipsum
        <lb/>Lorem gipsum
        <pb n="III"/>
        <lb/>Lorem hipsum
        <lb/>Lorem hipsum
        <lb/>Lorem hipsum
        <lb/>Lorem hipsum
    </p>
    <pb n="IV"/>
    <p>
        <lb/>Lorem dipsum
    </p>
</text>

From such a document, I am trying to get

  1. all text and elements between two pb elements, when @n of the first pb is given,
  2. and @n of the following and the preceding pb/@n, when @n of a pb is given.

Can anybody help? I am using XSLT 2.0 with SaxonCE.

EDIT: @ 2. the immediately following and immediately preceding.

1

There are 1 answers

0
Martin Honnen On BEST ANSWER

XPath 2.0 has operators << and >> so your first question would translate into //node()[. >> $pb1 and . << $pb2] (within XSLT code you need to escape << as &lt;&lt;, e.g. //node()[. >> $pb1 and . &lt;&lt; $pb2]). Selecting a pb element by its @n attribute should be obvious: <xsl:variable name="pb1" select="//pb[@n = 'foo']"/>. Defining a key <xsl:key name="by-n" match="pb" use="@n"/> with <xsl:variable name="pb1" select="key('by-n', 'foo')"/> might be more efficient.

Your second question might translate directly into an axis use: $pb1/(preceding::pb | following::pb)/@n. I am not sure however whether you want to find all preceding and following pb or only the immediately preceding respectively following ones.