Reputation: 11
I need to use xslt to identify and list all the duplicate elements within an xml file based on label's parent being //field @name="partya". Is there a simple way to achieve this? The xml is given below.
<table>
<entry>
<display>
<field name="partya">
<label>Abi</label>
</field>
<field name="partyb">
<label>Seddon</label>
</field>
<field name="validation-type">
<label>auto-valid</label>
</field>
...
</entry>
<entry>
<display>
<field name="partya">
<label>Abi</label>
</field>
Upvotes: 1
Views: 945
Reputation: 167506
In XSLT 2 or 3 you could group those label
elements and check whether there is more than one element in current-group()
:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
exclude-result-prefixes="#all"
version="3.0">
<xsl:output method="text" item-separator=" "/>
<xsl:template match="/">
<xsl:for-each-group select="//field[@name = 'partya']/label" group-by=".">
<xsl:if test="tail(current-group())">
<xsl:value-of select="."/>
</xsl:if>
</xsl:for-each-group>
</xsl:template>
</xsl:stylesheet>
https://xsltfiddle.liberty-development.net/ehVZvvA
In XSLT 1 you can use Muenchian grouping and check whether there is more than one item in a group:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:output method="text"/>
<xsl:key name="group" match="field[@name = 'partya']/label" use="."/>
<xsl:template match="/">
<xsl:apply-templates select="//field[@name = 'partya']/label[key('group', .)[2]][generate-id() = generate-id(key('group', .)[1])]"/>
</xsl:template>
<xsl:template match="label">
<xsl:if test="position() > 1"> </xsl:if>
<xsl:value-of select="."/>
</xsl:template>
</xsl:stylesheet>
https://xsltfiddle.liberty-development.net/ehVZvvA/1
Upvotes: 2