trim XML Node - Java XML

Java examples for XML:XML Node Operation

Description

trim XML Node

Demo Code

/**/*from w  ww .  j  a  v a 2  s . c o m*/
 *  Copyright 2012 Sven Ewald
 *
 *  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.
 */
//package com.java2s;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

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

public class Main {
    /**
     * @param domNode
     */
    public static void trim(final Node domNode) {
        assert domNode != null;
        assert (Node.TEXT_NODE != domNode.getNodeType());
        List<Text> removeMe = new LinkedList<Text>();
        NodeList childNodes = domNode.getChildNodes();
        for (Node child : nodeListToIterator(childNodes)) {
            if (Node.TEXT_NODE == child.getNodeType()) {
                if ((child.getNodeValue() == null)
                        || child.getNodeValue().trim().isEmpty()) {
                    removeMe.add((Text) child);
                }
                continue;
            }
            trim(child);
        }
        for (Text node : removeMe) {
            Node parent = node.getParentNode();
            if (parent != null) {
                parent.removeChild(node);
            }
        }
    }

    /**
     * @param childNodes
     * @return
     */
    private static Iterable<Node> nodeListToIterator(final NodeList nodeList) {
        return new Iterable<Node>() {

            @Override
            public Iterator<Node> iterator() {
                return new Iterator<Node>() {

                    private int pos = 0;

                    @Override
                    public boolean hasNext() {
                        return nodeList.getLength() > pos;
                    }

                    @Override
                    public Node next() {
                        return nodeList.item(pos++);
                    }

                    @Override
                    public void remove() {
                        throw new IllegalStateException();
                    }

                };
            }

        };
    }
}

Related Tutorials