XSLT: remove multiple elements having same child element content

Discussion in 'XML' started by Johannes Koch, Mar 5, 2004.

  1. 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>
    --
    Johannes Koch
    In te domine speravi; non confundar in aeternum.
    (Te Deum, 4th cent.)
    Johannes Koch, Mar 5, 2004
    #1
    1. Advertising

  2. Johannes Koch wrote:

    > 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>
    --

    Martin Honnen
    http://JavaScript.FAQTs.com/
    Martin Honnen, Mar 5, 2004
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Gerald Aichholzer
    Replies:
    2
    Views:
    2,481
    Gerald Aichholzer
    Jun 27, 2006
  2. Jeff Rodriguez
    Replies:
    23
    Views:
    1,087
    David Schwartz
    Dec 9, 2003
  3. Replies:
    4
    Views:
    2,513
  4. Aaron Davies
    Replies:
    4
    Views:
    4,200
    The Magpie
    Feb 11, 2009
  5. BananaQuaalude

    Remove child element that was dynamically created

    BananaQuaalude, Dec 17, 2007, in forum: Javascript
    Replies:
    2
    Views:
    542
    My Pet Programmer
    Dec 23, 2007
Loading...

Share This Page