xml child not deleted



I have a XML as given below. I want to recursively delete the empty tags from the same. As in once f gets deleted e should be deleted and as e gets deleted d is empty and hence that should also be deleted.



<Test>
<a>test</a>
<b>test</b>
<c></c>
<d>
<e>
<f> </f>
</e>
</d>
</Test>


result should be



<Test>
<a>test</a>
<b>test</b>
</Test>


I am able to delete tag but i am not able to delete tag as it has blank space. Altough I am able to identify this as a tag to be deleted but when I invoke the removeChild() on its parent it is not getting removed from the XML. In the code while debugging it shows the number of child of e after invoking removeChild() as zero. But still it remains in the xml??


Please can you help me what am I doing wrong.


Please find below my code which I am using.



for (Element childElement : toRemove) {
Node parentNode = childElement.getParentNode();
System.out.println("Removing null or empty node :: " + childElement.getNodeName());

if(parentNode!=null){
NodeList childList = parentNode.getChildNodes();
System.out.println("List of Childer before deleting :: " + childList.getLength());

//childElement.setNodeValue(null);

parentNode.removeChild(childElement);
clean(parentNode);

childList = parentNode.getChildNodes();
int childCount = childList.getLength();

for (int i = 0; i < childCount; i++) {
Node childNode = childList.item(i);
System.out.println("Childs :: " + childNode);
}

for (int i = 0; i < childCount; i++) {
Node childNode = childList.item(i);
if(childNode!=null){
System.out.println("Child before deleting :: " + childNode);

if (childNode instanceof Element == false){
if(childNode.getNodeValue().trim().isEmpty()){
System.out.println("found unwanted :: " + childNode.getNodeName());

parentNode.removeChild(childNode);
i--;
childCount--;
clean(parentNode);
}
}
}
}

childList = parentNode.getChildNodes();
System.out.println("List of Childer after deleting :: " + childList.getLength());
}

/*if(!parentNode.hasChildNodes()){
parentNodes.add((Element)parentNode);
}*/
}

No comments:

Post a Comment