Reputation: 802
I have a list of table elements under element named Query that may duplicate, I need to fetch distinct table elements (not its value but the tag/element name itself.
/ShopArea/Connection/Query/*
lists the table names including duplicates.
Below is the XML
<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="ShopArea.xslt"?>
<ShopArea>
<Connection name="Connection1">
<Report date="25-09-2011">
<Query id="1">
<TABLE1>1.1</TABLE1>
<TABLE2>1.2</TABLE2>
<TABLE3>1.3</TABLE3>
</Query>
<Query id="2">
<TABLE21>2.1</TABLE21>
<TABLE22>2.2</TABLE22>
<TABLE23>2.3</TABLE23>
</Query>
</Report>
<Report date="26-09-2011">
<Query id="1">
<TABLE1>26 1.1</TABLE1>
<TABLE2>26 1.2</TABLE2>
<TABLE3>26 1.3</TABLE3>
</Query>
<Query id="2">
<TABLE21>26 2.1</TABLE21>
<TABLE22>26 2.2</TABLE22>
<TABLE23>26 2.3</TABLE23>
</Query>
</Report>
</Connection>
</ShopArea>
I refered How to select unique nodes in XSLT but I'm not able to get it right.
Upvotes: 1
Views: 290
Reputation: 243599
I. XSLT 1.0. This transformation uses simple Muenchian grouping:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:key name="kChildByName" match="Query/*"
use="name()"/>
<xsl:template match=
"Query/*
[generate-id()
=
generate-id(key('kChildByName', name())[1])
]">
<xsl:value-of select="name()"/>
<xsl:text>
</xsl:text>
</xsl:template>
<xsl:template match="text()"/>
</xsl:stylesheet>
When applied on the provided XML document:
<ShopArea>
<Connection name="Connection1">
<Report date="25-09-2011">
<Query id="1">
<TABLE1>1.1</TABLE1>
<TABLE2>1.2</TABLE2>
<TABLE3>1.3</TABLE3>
</Query>
<Query id="2">
<TABLE21>2.1</TABLE21>
<TABLE22>2.2</TABLE22>
<TABLE23>2.3</TABLE23>
</Query>
</Report>
<Report date="26-09-2011">
<Query id="1">
<TABLE1>26 1.1</TABLE1>
<TABLE2>26 1.2</TABLE2>
<TABLE3>26 1.3</TABLE3>
</Query>
<Query id="2">
<TABLE21>26 2.1</TABLE21>
<TABLE22>26 2.2</TABLE22>
<TABLE23>26 2.3</TABLE23>
</Query>
</Report>
</Connection>
</ShopArea>
the wanted, correct result (all different names of elements that are children of a Query
) is produced:
TABLE1
TABLE2
TABLE3
TABLE21
TABLE22
TABLE23
II. XSLT 2.0: This transformation uses <xsl:for-each-group>
:
<xsl:stylesheet version="2.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xsl:output omit-xml-declaration="yes" indent="yes"/>
<xsl:template match="/*/*">
<xsl:for-each-group select="Report/Query/*"
group-by="name()">
<xsl:sequence select="current-grouping-key(), '
'"/>
</xsl:for-each-group>
</xsl:template>
<xsl:template match="text()"/>
</xsl:stylesheet>
Upvotes: 1