开发者

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

开发者 https://www.devze.com 2023-02-24 10:42 出处:网络
I have开发者_如何学运维 a xml structure as follows: <rurl modify=\"0\" children=\"yes\" index=\"8\" name=\"R-URL\">

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?


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.


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


Use removeChild()

http://download.oracle.com/javase/1.5.0/docs/api/org/w3c/dom/Node.html#removeChild(org.w3c.dom.Node)

0

精彩评论

暂无评论...
验证码 换一张
取 消