Reputation: 1828
I have a question on how to access the nodes from the XML using XSL.
I have a xml like this:
<Table>
<Row>
<Cell Type="Main" Id="980">Test22</Cell>
<Cell Type="SubElement">Test22 Sub Element1</Cell>
</Row>
<Row>
<Cell Type="Main" Id="123">Test</Cell>
<Cell/>
</Row>
<Row>
<Cell Type="SubElement">Test Sub Element1</Cell>
<Cell Type="Element">xyz</Cell>
</Row>
<Row>
<Cell Type="SubElement">Test Sub Element2</Cell>
<Cell Type="Element">abc</Cell>
</Row>
<Row>
<Cell Type="Main" Id="456">Test1</Cell>
<Cell/>
</Row>
<Row>
<Cell Type="SubElement">Test1 Sub Element1</Cell>
<Cell Type="Element">awe</Cell>
</Row>
<Row>
<Cell Type="SubElement">Test1 Sub Element2</Cell>
<Cell Type="Element">scd</Cell>
</Row>
</Table>
Now, I need to get the 1st Row's Id (i.e. Cell[Type='Main']/@Id) from the 2nd & 3rd Row's Element Cell (1st row is the parent row for 2nd & 3rd row). Similarly I need to access 4th Row's Id (i.e. Cell[Type='Main']/@Id) from the 5th & 6th Row (4th row is the parent row for 5th & 6th row).
I tried using xsl:variables but I couldn't assign values dynamically.
Please advise. Thanks in advance
Upvotes: 2
Views: 579
Reputation: 60414
Use the following expression within a template that is processing a SubElement
or Element
:
../preceding-sibling::Row[Cell/@Type='Main'][1]/Cell/@Id
For example:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>
<xsl:strip-space elements="*" />
<xsl:template match="Cell[@Type[.='SubElement' or .='Element']]">
[<xsl:value-of select="concat(., '; Parent ID: ',
../preceding-sibling::Row[Cell/@Type='Main'][1]/Cell/@Id)"/>]
</xsl:template>
<xsl:template match="Cell"/>
</xsl:stylesheet>
Outputs (spaces removed):
[Test Sub Element1; Parent ID: 123]
[xyz; Parent ID: 123]
[Test Sub Element2; Parent ID: 123]
[abc; Parent ID: 123]
[Test1 Sub Element1; Parent ID: 456]
[awe; Parent ID: 456]
[Test1 Sub Element2; Parent ID: 456]
[scd; Parent ID: 456]
Upvotes: 1
Reputation: 60236
Something like this should do the trick:
<xsl:template match="Table">
<xsl:foreach select="Row[Cell/@Type='Main']">
Id: <xsl:value-of select="Cell[@Type='Main']/@Id" />
Element 1: <xsl:value-of select="following-sibling::Row[Cell/@Type='Element'][1]" />
Element 2: <xsl:value-of select="following-sibling::Row[Cell/@Type='Element'][2]" />
</xsl:for-each>
</xsl:template>
Upvotes: 0