I’m trying to find a way to index nodes that contain a specific type of sub-node, and have them indexed starting at one and incrementing by one per each sub-node found. I tried using count() but this displays the position of the node in my code, not the index of the sub-node found. In other languages I would use a variable but this isn’t an option in XSLT.
I have read some examples of a recursive count using templates, but I’m not familiar enough with XSLT to integrate it into my existing code.
XML
<?xml version="1.0" encoding="UTF-8"?>
<entry>
<node>
<subnodeA>test_subnodeA1</subnodeA>
<subnodeB>test_subnodeB1</subnodeB>
</node>
<node>
<subnodeA>test_subnodeA2</subnodeA>
<subnodeB>test_subnodeB2</subnodeB>
</node>
<node>
<subnodeA>test_subnodeA3</subnodeA>
</node>
<node>
<subnodeA>test_subnodeA4</subnodeA>
<subnodeB>test_subnodeB3</subnodeB>
</node>
</entry>
XSLT
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="/">
<!-- Initial usage -->
<xsl:for-each select="node">
<xsl:value-of select="subnodeA"/>
<xsl:if test="subnodeB != ''">
<xsl:value-of select="position()"/>
</xsl:if>
</xsl:for-each>
<!-- Second usage -->
<xsl:for-each select="node">
<xsl:if test="subnodeB != ''">
<xsl:value-of select="position()"/>.
<xsl:value-of select="subnodeB"/>
</xsl:if>
</xsl:for-each>
</xsl:template>
I want to display something like
test_subnodeA1 1
test_subnodeA2 2
test_subnodeA3
test_subnodeA4 3
1 test_subnodeB1
2 test_subnodeB2
3 test_subnodeB3
But using my method I can only get
test_subnodeA1 1
test_subnodeA2 2
test_subnodeA3
test_subnodeA4 4
1 test_subnodeB1
2 test_subnodeB2
4 test_subnodeB3
Some entries have a few nodes with no subnodeB and then a node with one, so my lists start at 3, 4 or 5.
In the first case, you can get the position by counting preceding siblings
In the second case, you just want node elements with a subnodeB
Here is the example XSLT. Note that I have switched from using xsl:for-each to using xsl:apply-templates
This generates the following text output