如何在java中使用jdom从节点中删除子节点?
我的 xml 结构如下:
<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。目前我正在使用这段代码:
while(subchilditr.hasNext()){
Element subchild = (Element)subchilditr.next();
if (subchild.getText().equalsIgnoreCase(text)) {
message = subchild.getText();
update = "Success";
subchild.removeAttribute("priority");
subchild.removeContent();
}
但它并没有完全从 xml 文件中删除子元素。它给我留下了
<rurl-link/>
任何建议?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要这样做:
如果您尝试删除循环内的元素,您将收到
ConcurrentModificationException
。You'll need to do this:
If you try to remove an element inside of the loop you'll get a
ConcurrentModificationException
.如果您有父元素
rurl
,您可以使用方法 removeChild 或 删除子项。If you have the parent element
rurl
you can remove its children using the method removeChild or removeChildren.使用
removeChild()
http://download.oracle.com/javase/1.5.0/docs/api/org/w3c/dom/Node.html#removeChild(org.w3c.dom.节点)
Use
removeChild()
http://download.oracle.com/javase/1.5.0/docs/api/org/w3c/dom/Node.html#removeChild(org.w3c.dom.Node)