All,
I’m new to XSLT and facing a typical problem. Below is the problem details
Based on the data below, i needed to show ItemA/ANum element only when its of AName BBC and not part of ItemB/tempBNum
So desired result for the below data should be 0214,BBC, since its part of the ItemA, also is a BBC is does not appear in ItemB.
<myData>
<ItemA>
<ANum>0213</ANum>
<AName>OOC</AName>
</ItemA>
<ItemA>
<ANum>0031</ANum>
<AName>BBC</AName>
</ItemA>
<ItemA>
<ANum>0214</ANum>
<AName>BBC</AName>
</ItemA>
<ItemA>
<ANum>0044</ANum>
<AName>BBC</AName>
</ItemA>
<ItemB>
<tempBNum>0031</tempBNum>
</ItemB>
<ItemB>
<tempBNum>0044</tempBNum>
</ItemB>
</myData>
For this end, I tried putting in a logic of having Nested For Loops, only problem being nested loop should break when ItemAObj/ANum = tempBNum, but its not breaking and producing duplicate results.
<xsl:for-each select="myData/ItemA">
<xsl:variable name="ItemAObj" select="." />
Num = <xsl:value-of select="$ItemAObj/ANum"/>
<xsl:for-each select="/myData/ItemB">
<xsl:choose>
<xsl:when test="$ItemAObj/ANum!=tempBNum and $ItemAObj/AName='BBC'"> <xsl:value-of select="tempBNum"/>
<xsl:text> </xsl:text>
</xsl:when>
</xsl:choose>
</xsl:for-each>
</xsl:for-each>
Any help on this will be greatly appreciated.
You don’t need to use any
xsl:for-eachto solve the problem, much more you don’t need nestedxsl:for-each.In fact, the wanted
ItemAelements can be selected with a single XPath expression:Therefore a simple XSLT transformation that evaluates the above XPath expression and copies the result to the output is:
When this transformation is applied to the provided XML document:
the wanted, correct result is produced:
If we want just the values of the text nodes, just use the
string()function:Then the so modified transformation:
when applied on the same XML document (above), produces:
Note: If performance starts to matter, using keys could be the next step to increase the efficiency of the transformation.