How many <ItemName> elements will be there in output if the given XSL style sheet is applied on the given XML document?
-------------------XML Document-------------------
<?xml version="1.0"?>
<ItemsList>
<Items supplier="vinay">
<ItemName code="M1">Mouse</ItemName>
<ItemName code="M2">Mouse</ItemName>
<ItemName code="K1">KeyBoard</ItemName>
</Items>
<Items supplier="xyz">
<ItemName code="M1">Mouse</ItemName>
<ItemName code="M2">KeyBoard</ItemName>
<ItemName code="K2">KeyBoard</ItemName>
<ItemName code="K1">KeyBoard</ItemName>
</Items>
</ItemsList>
-------------------XSL Document----------------------
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl utput indent="yes" omit-xml-declaration="yes"/>
<xsl:key name="kCodeValue" match="ItemName" use="concat(@code,'::', .)"/>
<xsl:template match="/">
<ItemList>
<xsl:apply-templates/>
</ItemList>
</xsl:template>
<xsl:template match="text()"/>
<xsl:template match="ItemName[count(.| key('kCodeValue',concat(@code,'::', .))[1])=1]">
<xsl:copy-of select="."/>
</xsl:template>
</xsl:stylesheet>
IBM Certified Developer -XML and Related Technologies(141)<br />SCJP2 SCWCD
William Butler Yeats: All life is a preparation for something that probably will never happen. Unless you make it happen.
ItemName[0] M1::Mouse
ItemName[1] M2::Mouse
ItemName[2] K1::KeyBoard
ItemName[3] M1::Mouse
ItemName[4] M2::KeyBoard
ItemName[5] K2::KeyBoard
ItemName[6] K1::KeyBoard
This node-set will be having "kCodeValue" as its key name and the values shown above as repective key values.
Now if we say something like -
<xsl:for-each select="key("kCodeValue", "M1::Mouse")>.....
Here nodes ItemName[0] and ItemName[3]will be selected by the above xsl statement.
I think the entire things lies around this count() function -
<xsl:template match="ItemName[count(.| key('kCodeValue',concat(@code,'::', .))[1])=1]">
<xsl:copy-of select="."/>
</xsl:template>
key('kCodeValue',concat(@code,'::', .))
will return a node-set of 2 nodes for the repeating ones.
By saying
key('kCodeValue',concat(@code,'::', .))[1], i think we are comparing the current context of ItemName node(.) to be always equal to the first one in the key list. This is enforcing the condition of uniqueness.
"|" means union
William Butler Yeats: All life is a preparation for something that probably will never happen. Unless you make it happen.