FelHa
FelHa

Reputation: 1103

Process element depending on position of preceding sibling

Is there a way to handle an element <list_x> depending on the position of certain nodes on the preceding-sibling-axis?

XML Code:

<?xml version="1.0" encoding="UTF-8"?>
    <root>
        <text/>
        <text/>
        <text/>
        <list_num_start/>
        <list_num/>
        <list_num/>
        <list_x/>
        <text/>
        <text/>
        <text/>
        <list_square_start/>
        <list_square/>
        <list_square/>
        <list_x/>
    </root>

Template:

<xsl:template match="list_x">
    <xsl:element name="li">
        <xsl:attribute name="class"><xsl:value-of select="name()"/></xsl:attribute>
        <xsl:apply-templates/>
    </xsl:element>
    <xsl:choose>
        <xsl:when test="position(preceding-sibling::list_num_start[last()]) &lt; position(preceding-sibling::list_square_start[last()])">
            <xsl:text disable-output-escaping="yes">&lt;/ol&gt;</xsl:text>
        </xsl:when>
        <xsl:otherwise>...</xsl:otherwise>
    </xsl:choose>
</xsl:template>

Unfortunately position() does not allow any arguments.

Output should be:

<root>
    <text/>
    <text/>
    <text/>
    <ol>
        <li class="list_num_start"/>
        <li class="list_num"/>
        <li class="list_num"/>
        <li class="list_x"/>
    </ol>
    <text/>
    <text/>
    <text/>
    <ul>
        <li class="list_square_start"/>
        <li class="list_square"/>
        <li class="list_square"/>
        <li class="list_x"/>
    </ul>
</root>

Upvotes: 0

Views: 280

Answers (1)

hr_117
hr_117

Reputation: 9627

You may try:

  <xsl:when test="count(preceding-sibling::list_num_start[1]/preceding-sibling::*) &lt; 
             count(preceding-sibling::list_square_start[1]/preceding-sibling::*)">

This counts the element before the one you are looking for.

I changed list_num_start[last()] to list_num_start[1] because I assume you are looking for the element list_num_start direct before the current one.

Upvotes: 1

Related Questions