Java tutorial
//package com.java2s; /*********************************************************************************************************************** * Copyright (c) 2008 empolis GmbH and brox IT Solutions GmbH. All rights reserved. This program and the accompanying * materials are made available under the terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html * * Contributors: Daniel Stucky (empolis GmbH) - initial API and implementation **********************************************************************************************************************/ import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class Main { /** * Traverses through a DOM tree starting at the given element and removes all those text-nodes from it that only * contain white spaces. * * @param parent * the parent Element */ public static void removeWhitespaceTextNodes(Element parent) { final NodeList nl = parent.getChildNodes(); for (int i = 0; i < nl.getLength(); i++) { final Node child = nl.item(i); if (child.getNodeType() == Node.TEXT_NODE) { if (child.getNodeValue().trim().length() == 0) { parent.removeChild(child); i--; // since the child is removed counting up must be made undone } } else if (child.getNodeType() == Node.ELEMENT_NODE && child.getChildNodes().getLength() > 0) { removeWhitespaceTextNodes((Element) child); } } } }