XSLT: remove multiple elements having same child element content

J

Johannes Koch

How to remove multiple elements with the same child element content?

E.g. input:
<root>
<foo>
<bar>ABC</bar>
</foo>
<foo>
<bar>DEF</bar>
</foo>
<foo>
<bar>ABC</bar>
</foo>
<foo>
<bar>ABC</bar>
</foo>
</root>

The other foo elements with bar='ABC' should be removed.

output:
<root>
<foo>
<bar>ABC</bar>
</foo>
<foo>
<bar>DEF</bar>
</foo>
</root>
 
M

Martin Honnen

Johannes said:
How to remove multiple elements with the same child element content?

E.g. input:
<root>
<foo>
<bar>ABC</bar>
</foo>
<foo>
<bar>DEF</bar>
</foo>
<foo>
<bar>ABC</bar>
</foo>
<foo>
<bar>ABC</bar>
</foo>
</root>

The other foo elements with bar='ABC' should be removed.

output:
<root>
<foo>
<bar>ABC</bar>
</foo>
<foo>
<bar>DEF</bar>
</foo>
</root>

I think defining a key and using generate-id is one way:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">

<xsl:eek:utput method="xml" indent="yes" />

<xsl:key name="barKey" match="foo" use="bar" />

<xsl:template match="root">
<xsl:copy>
<xsl:apply-templates select="foo[generate-id(.) =
generate-id(key('barKey', ./bar))]" />
</xsl:copy>
</xsl:template>

<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()" />
</xsl:copy>
</xsl:template>

</xsl:stylesheet>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Staff online

Members online

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,008
Latest member
Rahul737

Latest Threads

Top