简体   繁体   中英

Delete Node in XML Structure Java DOM

I'm trying to delete a Node from a XML File parsed with DOM in Java.

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.

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. basically, when you remove the child node, if modifies the NodeList so that all the following nodes get shifted back one index. (similar to removing elements from a List while iterating over the list using indexes). a simple fix would be to add "--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);
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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