Java XML Node Normalize normalize(Node node)

Here you can find the source of normalize(Node node)

Description

Normalizes the DOM structure starting from the given node

License

Apache License

Parameter

Parameter Description
node the node to start the normalization

Declaration

protected static void normalize(Node node) 

Method Source Code

//package com.java2s;
/*/*from   w w w.  j  av a2 s. co  m*/
 * Copyright 2002-2008 The Gong Project (http://gong.ust.hk)
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

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

public class Main {
    /**
     * Normalizes the DOM structure starting from the given node
     * @param node the node to start the normalization
     */
    protected static void normalize(Node node) {
        NodeList nodeList = node.getChildNodes();

        // Join any consecutive text nodes
        for (int index = 0; index < nodeList.getLength() - 1; index++) {
            Node child = nodeList.item(index);
            if (child.getNodeType() == Node.TEXT_NODE) {
                for (index++; index < nodeList.getLength(); index++) {
                    Node next = nodeList.item(index);
                    if (next.getNodeType() != Node.TEXT_NODE)
                        break;

                    String text = child.getNodeValue() + next.getNodeValue();
                    child.setNodeValue(text);

                    node.removeChild(next);
                }
            }
        }

        nodeList = node.getChildNodes();

        // Remove any empty text nodes
        for (int index = 0; index < nodeList.getLength(); index++) {
            Node child = nodeList.item(index);
            if (child.getNodeType() == Node.TEXT_NODE) {
                String text = child.getNodeValue();
                if (text.trim().length() == 0) {
                    node.removeChild(child);
                    index--;
                }
            } else
                normalize(child);
        }
    }
}

Related

  1. normalize(Node node)
  2. normalize(Node node)