Java tutorial
//package com.java2s; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.Text; public class Main { /** * Recursively removes all text nodes containing whitespace only from a document element. Also * trims leading and trailing whitespace from text nodes. * * @param e The root document element. */ public static void removeWhitespaceNodes(Element e) { NodeList children = e.getChildNodes(); for (int i = children.getLength() - 1; i >= 0; i--) { Node child = children.item(i); if (child instanceof Text && ((Text) child).getData().trim().length() == 0) e.removeChild(child); else if (child instanceof Text) child.setTextContent(((Text) child).getData().trim()); else if (child instanceof Element) removeWhitespaceNodes((Element) child); } } }