Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.util.ArrayList;
import java.util.List;

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

public class Main {
    private static List<Node> getNonEmptyChildNodes(Node parent) {
        NodeList nl = parent.getChildNodes();
        List<Node> ret = new ArrayList<Node>();
        for (int i = 0; i < nl.getLength(); i++) {
            if (!(nl.item(i) instanceof Text && ((Text) nl.item(i)).getTextContent().trim().length() == 0))
                ret.add(nl.item(i));
        }
        return ret;
    }

    /** Returns concatenated, then trimmed text and CDATA sections, or null if any other kinds of
    child nodes are present. */
    public static String getTextContent(Node parent) {
        List<Node> childNodes = getNonEmptyChildNodes(parent);
        StringBuilder ret = new StringBuilder();
        /* This loop is necessary even under normalization, because text nodes may be adjacent to CDATA
        sections. */
        for (Node childNode : childNodes) {
            if (!(childNode instanceof Text))
                return null;
            ret.append(((Text) childNode).getTextContent());
        }
        return ret.toString().trim();
    }
}