Java XML Node Remove removeEmptyHeadings(Node root)

Here you can find the source of removeEmptyHeadings(Node root)

Description

Remove empty text:h elements.

License

Open Source License

Parameter

Parameter Description
root The document element (or "root element").

Declaration

private static void removeEmptyHeadings(Node root) 

Method Source Code

//package com.java2s;
/**/*from   w  w w .  ja  va  2s  . c  o  m*/
 *  odt2daisy - OpenDocument to DAISY XML/Audio
 *
 *  (c) Copyright 2008 - 2012 by Vincent Spiewak, All Rights Reserved.
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Lesser Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public License along
 *  with this program; if not, write to the Free Software Foundation, Inc.,
 *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

import org.w3c.dom.Element;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main {
    /**
     * Remove empty <code>text:h</code> elements.
     * 
     * @param root The document element (or "root element").
     */
    private static void removeEmptyHeadings(Node root) {

        // for each text:h
        // remove empty headings
        NodeList hNodes = ((Element) root).getElementsByTagName("text:h");
        for (int i = 0; i < hNodes.getLength(); i++) {

            Node node = hNodes.item(i);

            if (node.getChildNodes().getLength() > 0) {

                boolean empty = true;

                for (int j = 0; j < node.getChildNodes().getLength(); j++) {
                    if (!node.getChildNodes().item(j).getTextContent().trim().equals("")) {
                        empty = false;
                    }
                }

                if (empty) {
                    node.getParentNode().removeChild(node);
                    i--;
                }

            } else {
                if (node.getTextContent().trim().equals("")) {
                    node.getParentNode().removeChild(node);
                    i--;
                }

            }
        }

    }
}

Related

  1. removeAll(Node node, short nodeType, String name)
  2. removeContents(Node parent)
  3. removeElement(Element parent, String tagName)
  4. removeElements(Node parent, String nature)
  5. removeElementXML(Node node, short nodeType, String name)
  6. removeEmptyHeadings(Node root)
  7. removeEmptyLines(Node node)
  8. removeEmptyNodes(Node node)
  9. removeEmptyParagraphs(Node root)