Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting data in xml file not working correctly

Tags:

java

xml

I am developing a XML Editor and when user clicks delete on a type the application shall delete the whole type. but its not its only deleting the content but leaving the tags.

<type>
<OBJECT_TYPE/>
<prop/>
<param/>
<param/>
<param/>
<param/>
<param/>
<param/>
<param/>
<param/>
<param/>
<param/>
<param/>
<param/>
<param/>
<param/>
</type>
<type>
<OBJECT_TYPE/>
<prop/>
<param/>
<param/>
<param/>
</type>
<type>
<OBJECT_TYPE/>
<prop/>
<param/>
<param/>
</type>

So basiclly all the data is gone but its leaving this tags and I want to delte them aswell. how to do it?

My code :

NodeList type = (NodeList) doc.getElementsByTagName("type").item(x);
            System.out.println("type : " + type);

            for (int i = 0; i < type.getLength(); i++) {

                Node curNode = (Node) type.item(i);
                System.out.println(" Node name : " + curNode.getChildNodes());
                removeChilds(curNode);

            }

            // Save the new update
            save(doc);

public static void removeChilds(Node node) {
        while (node.hasChildNodes())
            node.removeChild(node.getFirstChild());
    }
like image 249
Sembrano Avatar asked Dec 06 '25 10:12

Sembrano


1 Answers

I think you are doing wrong DOM tree navigation. The item already returns you a Node for <type> tag. You just need to delete it:

Node type = doc.getElementsByTagName("type").item(x);
type.getParentNode().removeChild(type);

That are you doing in your code - you are casting Node to NodeList (xml elements are also list of children nodes), so your for loop iterates over children of the <type>. Then in each child (such as prop and param in your example) you iterate over children again and remove each of them. So you never delete type node.

like image 109
kan Avatar answered Dec 08 '25 00:12

kan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!