如何在java中使用jdom从节点中删除子节点

如何在java中使用jdom从节点中删除子节点

本文介绍了如何在java中使用jdom从节点中删除子节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个xml结构如下:

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>

现在,我想删除一个子节点,其中text等于http。目前我正在使用此代码:

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();
    }

但它并没有从xml文件中完全删除子元素。它离开了我

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

<rurl-link/>

有什么建议吗?

推荐答案

你需要这样做:

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);
}

如果您尝试删除循环内的元素,您将获得一个 ConcurrentModificationException

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

这篇关于如何在java中使用jdom从节点中删除子节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 17:27