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

ぐ巨炮叔叔 提交于 2019-12-31 04:26:09

问题


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?


回答1:


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.




回答2:


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




回答3:


Use removeChild()

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



来源:https://stackoverflow.com/questions/5643346/how-to-remove-a-child-from-from-a-node-using-jdom-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!