简体   繁体   English

删除XML结构Java DOM中的节点

[英]Delete Node in XML Structure Java DOM

I'm trying to delete a Node from a XML File parsed with DOM in Java. 我正在尝试从Java中用DOM解析的XML文件中删除节点。

private Node deleteChildNode (Node node, String nodeName )
{
    Node tempNode = null;
    NodeList nl = node.getChildNodes();
    for (int i = 0; i < nl.getLength(); i++)
    {
        tempNode = nl.item(i);
        if (tempNode.getNodeName().equals(nodeName))
        {                   
            tempNode= node.removeChild(tempNode);                   
        }        
    }
    return node;
}

Calling with: 致电:

nodeClone = deleteChildNode(nodeClone, "L123");

But the Node has not been deleted. 但是节点尚未删除。

NodeList nl = nodeClone.getChildNodes();
        for (int i = 0; i < nl.getLength(); i++)
            System.out.println(nl.item(i).getNodeName());

Shows the "L123" Node. 显示“ L123”节点。

Thanks in advance! 提前致谢!

If you have more than one node with the node name under the given node, then your code will not work because you will skip nodes. 如果在给定节点下具有多个节点名称的节点,则您的代码将不起作用,因为您将跳过节点。 using a NodeList while removing nodes is a bit tricky. 在删除节点的同时使用NodeList有点棘手。 basically, when you remove the child node, if modifies the NodeList so that all the following nodes get shifted back one index. 基本上,当您删除子节点时,如果要修改NodeList,以便随后的所有节点都移回一个索引。 (similar to removing elements from a List while iterating over the list using indexes). (类似于在使用索引遍历列表时从列表中删除元素)。 a simple fix would be to add "--i;" 一个简单的解决方法是添加“ --i;” after you remove a child node. 删除子节点后。

I use this little handy method to clear children of the passed node: 我使用这种方便的方法来清除传递的节点的子节点:

public static void clearChildNodes(Node node){
    while(node.hasChildNodes()){
        NodeList nList = node.getChildNodes();
        int index = node.getChildNodes().getLength() - 1;

        Node n = nList.item(index);
        clearChildNodes(n);
        node.removeChild(n);
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM