DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Egbert has posted 3 posts at DZone. View Full User Profile

Remove Empty Nodes From Dom Document

  • submit to reddit
        // Snippit to remove an empty node from the document.
// Node node contains the node (or whole DOM document) from which you want to remove.
// String nameToRemove is the name of the Node you want to remove.

	private static void removeEmptyNodes(Node node, String nameToRemove) {
		NodeList nodeList = node.getChildNodes();
		for(int i=0; i < nodeList.getLength(); i++){
			Node childNode = nodeList.item(i);
			String nodeName = childNode.getNodeName(); 
			if(nodeName.equals(nameToRemove) && childNode.getTextContent().equals("")){

			removeEmptyNodes(childNode, nameToRemove);