dMilan
dMilan

Reputation: 257

How to get last 2 nodes previous specific node?

This is my xml:

<Line>
    <Item>
     <Id>1</Id>
     <Name>A</Name>
     <Unit>AA</Unit>
     <Value>5</Value>
    </Item>
</Line>
<Line>
    <Item>
     <Id>2</Id>
     <Name>B</Name>
     <Unit>Test</Unit>
     <Value>5</Value>
    </Item>
</Line>
<Line>
    <Item>
     <Id>3</Id>
     <Name>C</Name>
     <Unit>AA</Unit>
     <Value>5</Value>
    </Item>
</Line>
<Line>
    <Item>
     <Id>4</Id>
     <Name>D</Name>
     <Unit>AA</Unit>
     <Value>5</Value>
    </Item>
</Line>
<Line>
    <Item>
     <Id>5</Id>
     <Name>E</Name>
     <Unit>AA</Unit>
      <Value>5</Value>
    </Item>
</Line>

How to get all nodes which are at first and second position after nodes with Unit= Test. In this case, node with Id= 2 have Unit = Test so I want to display nodes with Id = 3 and Id = 4. Thanks

Upvotes: 0

Views: 46

Answers (1)

Tim C
Tim C

Reputation: 70638

The expression you want is this...

<xsl:copy-of select="//Line[Item/Unit='Test']/following-sibling::Line[position() &lt;= 2]" />

This will work regardless of what the current node is.

Alternatively, you could split it out in to templates. For example

<xsl:template match="/*">
  <xsl:apply-templates select="//Line[Item/Unit='Test']" />
</xsl:template>

<xsl:template match="Line">
  <xsl:copy-of select="following-sibling::Line[position() &lt;= 2]" />
</xsl:template>  

If you want to get all nodes except 3 and 4, try this expression instead

<xsl:copy-of select="//Line[not(preceding-sibling::Line[position() &lt;= 2][Item/Unit = 'Test'])]" />

Upvotes: 1

Related Questions