Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilderFactory;
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;

public class Main {

    public static void main(String[] argv) throws Exception {
        Document doc = createXmlDocument("root");

        System.out.println(documentToString(doc));

    }

    /**
     * Start a new XML Document.
     * @param rootName The name of the Document root Element (created here)
     * @return the Document
     * @throws DomException
     */
    public static Document createXmlDocument(String rootName) throws Exception {
        DocumentBuilderFactory factory;

        factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(false);

        Document document = factory.newDocumentBuilder().newDocument();
        Element root = document.createElement(rootName);

        document.appendChild(root);
        return document;
    }

    public static String documentToString(Document document) {
        try {
            TransformerFactory tf = TransformerFactory.newInstance();
            Transformer trans = tf.newTransformer();
            StringWriter sw = new StringWriter();
            trans.transform(new DOMSource(document), new StreamResult(sw));
            return sw.toString();
        } catch (TransformerException tEx) {
            tEx.printStackTrace();
        }
        return null;
    }
}