Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;

import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;

import javax.xml.transform.dom.DOMSource;

import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

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

public class Main {
    private final static String CHAR_NBSP = "\u00A0";

    public static String getContent(Node n) {
        assertNotNull("node == null", n);
        StringBuilder result = new StringBuilder();
        if (n.getNodeType() == Node.TEXT_NODE) {
            result.append(n.getNodeValue());
        }
        NodeList childNodes = n.getChildNodes();
        for (int i = 0; i < childNodes.getLength(); i++) {
            Node n2 = childNodes.item(i);
            result.append(getContent(n2));
        }

        String tmp = result.toString();
        return tmp.replaceAll(CHAR_NBSP, " ");
    }

    private static void assertNotNull(String msg, Object o) {
        if (o == null) {
            throw new IllegalStateException(msg);
        }
    }

    public static List<Element> getChildNodes(Element parent, String name) {
        List<Element> result = new ArrayList<Element>();
        NodeList childNodes = parent.getChildNodes();
        for (int i = 0; i < childNodes.getLength(); i++) {
            Node n = childNodes.item(i);
            if (name.equals(n.getNodeName())) {
                result.add((Element) n);
            }
        }
        return result;
    }

    public static String toString(Document doc) {
        try {
            StringWriter sw = new StringWriter();
            Source source = new DOMSource(doc);
            Result result = new StreamResult(sw);

            TransformerFactory tf = TransformerFactory.newInstance();
            tf.setAttribute("indent-number", new Integer(4));
            Transformer xformer = tf.newTransformer();
            xformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
            xformer.setOutputProperty(OutputKeys.INDENT, "yes");
            xformer.transform(source, result);
            return sw.toString();
        } catch (TransformerException e) {
            throw new RuntimeException(e);
        }
    }
}