XML: JDOM: removing all elements with certain attribute

Discussion in 'Java' started by cyberco, Nov 7, 2007.

  1. cyberco

    cyberco Guest

    Using JDOM I want to remove all elements with attribute uid="x" from
    the following xml:


    =======================================
    <root>
    <ele>
    <sub uid="x">
    bla
    </sub>
    </ele>
    <ele uid="x">
    boe
    </ele>
    </root>

    =======================================

    How can I do that? Iterating and removing at the same time gives me
    concurrent modification exceptions.

    2B
     
    cyberco, Nov 7, 2007
    #1
    1. Advertising

  2. cyberco

    cyberco Guest

    Using XPath seemed to be the easiest way:

    ==================================================================
    Document doc = new SAXBuilder().build(new StringReader(xml));
    List<Element> Eles = XPath.selectNodes(doc.getRootElement(), "//
    *[@uid='x']");
    for (Element e: Eles) {
    e.getParentElement().removeContent(e);
    }

    //optionally print it
    System.out.println(new XMLOutputter().outputString(doc));
    ==================================================================
     
    cyberco, Nov 7, 2007
    #2
    1. Advertising

  3. cyberco

    Roedy Green Guest

    On Wed, 07 Nov 2007 17:29:54 -0000, cyberco <> wrote,
    quoted or indirectly quoted someone who said :

    >How can I do that? Iterating and removing at the same time gives me
    >concurrent modification exceptions.


    see http://mindprod.com/jgloss/iterator.html#REMOVE
    --
    Roedy Green Canadian Mind Products
    The Java Glossary
    http://mindprod.com
     
    Roedy Green, Nov 7, 2007
    #3
    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. Wendy S
    Replies:
    1
    Views:
    6,458
    Darren Davison
    Aug 5, 2003
  2. Bernd Oninger
    Replies:
    4
    Views:
    12,691
    GIMME
    Jun 21, 2004
  3. Tinker
    Replies:
    4
    Views:
    5,434
    Harry Bosch
    Oct 9, 2005
  4. Bernd Oninger
    Replies:
    3
    Views:
    2,924
    GIMME
    Jun 21, 2004
  5. vj
    Replies:
    2
    Views:
    1,158
Loading...

Share This Page