VJain
VJain

Reputation: 21

How to get the next node's child value inside a for-loop in XSLT

I am trying to access a value from the next node inside a for loop in XSLT.

The XML source is :

<?xml version="1.0" encoding="UTF-8"?>
<tree>
<parent>
    <id>1</id>
    <child>
        <effective_date>01-09-2019</effective_date>
        <hours>10</hours>
        <dept>1</dept>
    </child>
    <child>
        <effective_date>01-10-2019</effective_date>
        <hours>20</hours>
        <dept>1</dept>
    </child>
    <child>
        <effective_date>01-10-2019</effective_date>
        <class>A</class>
    </child>
</parent>
    <parent>
        <id>2</id>
        <child>
            ...
        </child>
        <child>
            ..
        </child>
    </parent>
</tree> 

The desired output is that I want the next child node's Effective_date value in first validUntil tag in result like below :

<?xml version="1.0" encoding="UTF-8"?>
<employees>
    <departments>
        <department>
            <code>1</code>
            <weeklyHours>10</weeklyHours>
            <validFrom>2019-09-09</validFrom>
            <validUntil>2019-10-01</validUntil
        </department>
        <department>
            <code>1</code>
            <weeklyHours>20</weeklyHours>
            <validFrom>2019-10-01</validFrom>
            <validUntil/>
        </department>
    </departments>
</employees>

In my original xslt, I am inside a for loop, which I am entering conditionally based on whether a child element has change in hours or not. So this has to be accessed inside a for loop.

Upvotes: 0

Views: 327

Answers (1)

Michael Kay
Michael Kay

Reputation: 163322

If the xsl:for-each is iterating over sibling elements, then you can get the next element using following-sibling::*

If you are iterating over an arbitrary sequence $SEQ, then you can get the next element using:

  • XSLT 2.0: subsequence($SEQ, position()+1, 1)

  • XSLT 1.0: <xsl:variable name="p" select="position()"/><xsl:.... select="$SEQ[$p+1]"/>

Don't make the mistake of using $SEQ[position()+1] - the value of position() changes within a predicate.

Upvotes: 1

Related Questions