Maverick
Maverick

Reputation: 2760

How to remove a child from from a node using jdom in java?

I have a xml structure as follows:

<rurl modify="0" children="yes" index="8" name="R-URL">
    <status>enabled</status>
    <rurl-link priority="3">http</rurl-link>
    <rurl-link priority="5">http://localhost:80</rurl-link>
    <rurl-link priority="4">abc</rurl-link>
    <rurl-link priority="3">b</rurl-link>
    <rurl-link priority="2">a</rurl-link>
    <rurl-link priority="1">newlinkkkkkkk</rurl-link>
</rurl>

Now, I want to remove a child node, where text is equal to http. currently I am using this code:

while(subchilditr.hasNext()){
    Element subchild = (Element)subchilditr.next();
    if (subchild.getText().equalsIgnoreCase(text)) {
        message = subchild.getText();
        update = "Success";
        subchild.removeAttribute("priority");
        subchild.removeContent();
    }

But it is not completely removing the sub element from xml file. It leaves me with

<rurl-link/>

Any suggestions?

Upvotes: 2

Views: 5655

Answers (3)

WhiteFang34
WhiteFang34

Reputation: 72069

You'll need to do this:

List<Element> elements = new ArrayList<Element>();

while (subchilditr.hasNext()) {
    Element subchild = (Element) subchilditr.next();
    if (subchild.getText().equalsIgnoreCase(text)) {
        elements.add(subchild);
    }
}

for (Element element : elements) {
    element.getParent().removeContent(element);
}

If you try to remove an element inside of the loop you'll get a ConcurrentModificationException.

Upvotes: 5

Benjamin Muschko
Benjamin Muschko

Reputation: 33456

If you have the parent element rurl you can remove its children using the method removeChild or removeChildren.

Upvotes: 0

Related Questions