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.Attr;

import org.w3c.dom.Element;

import org.w3c.dom.Text;

public class Main {
    public static String nodesToString(List<Object> nodes) {
        String result = "";
        for (Object node : nodes) {
            result += nodeToString(node);
        }
        return result;
    }

    public static String nodeToString(Object node) {
        String result = "";
        if (node instanceof String) {
            String str = ((String) node).replaceAll("\\s+", " ").trim();
            result += str;
        } else if (node instanceof Text) {
            String str = ((Text) node).getTextContent().replaceAll("\\s+", " ").trim();
            result += str;
        } else if (node instanceof Element) {
            Element en = (Element) node;
            result += "<" + en.getTagName();
            for (int j = 0; j < en.getAttributes().getLength(); j++) {
                Attr attr = (Attr) en.getAttributes().item(j);
                //if (!(attr.getNamespaceURI() != null && attr.getNamespaceURI().equals("http://www.w3.org/2000/xmlns/") && (attr.getLocalName().equals("xmlns") || attr.getLocalName().equals("xsi")))) {
                result += " " + attr.getName() + "=\"" + attr.getValue() + "\"";
                //}
            }
            if (en.getChildNodes().getLength() == 0) {
                result += "/>";
            } else {
                result += ">";
                ArrayList<Object> children = new ArrayList<Object>();
                for (int i = 0; i < en.getChildNodes().getLength(); i++) {
                    children.add(en.getChildNodes().item(i));
                }
                result += nodesToString(children);
                result += "</" + en.getTagName() + ">";
            }
        }
        return result;
    }
}