Reputation: 173
I need to read an XML and depending on the type of one of the child nodes need to run different logic. As shown in the example below, i need to increment the counter based on Type a or b. This is to identify the relative position of the Item based on Type a or b.
<List>
<Item>
<Type>a</Type>
<value>2</value>
</Item>
<Item>
<Type>b</Type>
<value>1</value>
</Item>
<Item>
<Type>b</Type>
<value>3</value>
</Item>
<Item>
<Type>a</Type>
<value>4</value>
</Item>
</List>
I'm running foreach loop on Item
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output encoding="UTF-8" indent="yes" method="xml" version="1.0"/>
<xsl:template match="/">
<JSON xmlns="">
{
<xsl:variable name="counter" select="0" />
<xsl:for-each select="List/Item">
<xsl:if test="Type='a'">
<xsl:value-of select="$counter"></xsl:value-of>
<xsl:variable name="counter" select="$counter + 1" />
</xsl:if>
</xsl:for-each>
}
</JSON>
</xsl:template>
</xsl:stylesheet>
The output is 0 0
Upvotes: 0
Views: 399
Reputation: 117003
If - as it seems - you only want to number the Item
s whose Type
is "a"
, why can't you do simply:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:template match="/List">
<JSON>
<xsl:text> { </xsl:text>
<xsl:for-each select="Item[Type='a']">
<xsl:value-of select="position()"/>
<xsl:text>-- </xsl:text>
</xsl:for-each>
<xsl:text>} </xsl:text>
</JSON>
</xsl:template>
</xsl:stylesheet>
Upvotes: 1
Reputation: 173
I solved it by using group-by logic within foreach to get the relative position instead of depending on counter
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output encoding="UTF-8" indent="yes" method="xml" version="1.0"/>
<xsl:template match="/">
<JSON xmlns="">
{
<xsl:variable name="counter" select="0" />
<xsl:for-each-group select="List/Item" group-by="Type='a'">
<xsl:for-each select="current-group()">
<xsl:if test="current-grouping-key() = true()">
<xsl:value-of select="position()"></xsl:value-of>--
</xsl:if>
</xsl:for-each>
</xsl:for-each-group>
}
</JSON>
</xsl:template>
</xsl:stylesheet>
Output:
{
1--
2--
3--
}
Upvotes: 0