Java 怎么修剪XML节点

2019年8月3日23:45:44Java 怎么修剪XML节点已关闭评论 410 1088字阅读3分37秒

1.简介

Java 怎么修剪XML节点?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */

 


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 {
    
    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);
            }
        }
    }

    
    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();
                    }

                };
            }

        };
    }
}

 
继续阅读
编程十万个怎么办