Java tutorial
//package com.java2s; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.Text; public class Main { public static Element removeElementContentWhitespace(Element root) { boolean foundElt = false; for (Node n1 = root.getFirstChild(); n1 != null; n1 = n1.getNextSibling()) { if (n1.getNodeType() != Node.ELEMENT_NODE) continue; foundElt = true; removeElementContentWhitespace(Element.class.cast(n1)); } if (foundElt) { Node n1 = root.getFirstChild(); while (n1 != null) { Node n2 = n1.getNextSibling(); if (n1.getNodeType() == Node.TEXT_NODE && isEmptyText(Text.class.cast(n1))) { root.removeChild(n1); } n1 = n2; } } return root; } public static boolean isEmptyText(Text txt) { String s = txt.getData(); for (int i = 0; i < s.length(); ++i) { if (!Character.isWhitespace(s.charAt(i))) return false; } return true; } }