Java tutorial
//package com.java2s; //License from project: Open Source License import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Main { private static void cleanDocument(final Document document) throws XPathExpressionException { document.getDocumentElement().normalize(); removeEmptyTextNodes(document); } private static void removeEmptyTextNodes(final Document document) throws XPathExpressionException { final XPath xPath = XPathFactory.newInstance().newXPath(); final NodeList nodeList = (NodeList) xPath.evaluate("//text()[normalize-space()='']", document, XPathConstants.NODESET); for (int i = 0; i < nodeList.getLength(); ++i) { final Node node = nodeList.item(i); node.getParentNode().removeChild(node); } } }