[xsl] Resolving Variable Redefining Issues in a For Each

Subject: [xsl] Resolving Variable Redefining Issues in a For Each
From: "Sian Mace" <sianmace@xxxxxxxxxxx>
Date: Wed, 30 Mar 2005 10:58:47 +0000
Hi,

Below are my XML and XSL

<Root>
   <Wrapper>
       <Detail>
           <Unit RecordID="1" Code="1" Total="2" />
           <Unit RecordID="1" Code="1" Total="2" />
           <Unit RecordID="1" Code="2" Total="2" />
           <Unit RecordID="1" Code="2" Total="2" />
           <Unit RecordID="1" Code="3" Total="2" />
           <Unit RecordID="2" Code="3" Total="2" />
           <Unit RecordID="2" Code="3" Total="2" />
           <Unit RecordID="2" Code="4" Total="2" />
           <Unit RecordID="2" Code="4" Total="2" />
        </Detail>
   </Wrapper>
</Root>

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"; xmlns:script="urn:my-namespace">
<xsl:template match="/">
<xsl:element name="Root">


<xsl:variable name="URecordID" select="/Root/Wrapper/Detail/Unit[not(./@RecordID=preceding::Unit/@RecordID)]"/>

<xsl:for-each select="$URecordID">
<xsl:variable name="thisRID" select="."/>
<xsl:variable name="RecordIDCodes" select="/Root/Wrapper/Detail/Unit[./@RecordID=$thisRID/@RecordID]"/>
<xsl:element name="Record">


					<xsl:attribute name="Type">
						<xsl:value-of select="$thisRID/@RecordID"/>
					</xsl:attribute>

<xsl:variable name="URecordIDCodes" select="$RecordIDCodes[not(./@Code=preceding::Unit/@Code)]"/>
<xsl:for-each select="$URecordIDCodes">
<xsl:variable name="thisCodes" select="."/>
<xsl:variable name="UCode" select="$RecordIDCodes[./@Code=$thisCodes/@Code]"/>
<xsl:element name="RCVCTN">
<xsl:attribute name="Code">
<xsl:value-of select="$thisCodes/@Code"/>
</xsl:attribute>
<xsl:attribute name="Total">
<xsl:value-of select="sum($UCode/@Total)"/>
</xsl:attribute>
</xsl:element>
</xsl:for-each>
</xsl:element>
</xsl:for-each>


		</xsl:element>
	</xsl:template>
</xsl:stylesheet>


This Should output the data first grouped by Record ID, Then By Unique Codes for that Record ID, totalling the Total column.


The problem is re assigning the variable in the for loop. I know this is the problem and why, but want some help finding a work around.

If you run the xml and xsl as a test, you should see that the output should be:

Record Type 1
   Code - 1 Total - 4
   Code - 2 Total - 4
   Code - 3 Total - 2
Record Type 2
   Code - 3 Total - 4
   Code - 4 Total - 4

What i actually get is
Record Type 1
   Code - 1 Total - 4
   Code - 2 Total - 4
   Code - 3 Total - 2
Record Type 2
   Code - 4 Total - 4

As you can see, Code 3 is missing from record type 2. This is because it has already occured for Record type 1 and cannot be reassigned in the variable.

I need to resolve this, and would appriciate some help

Thanks
Sian

Current Thread