Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

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

public class Main {

    public static void main(String args[]) throws Exception {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        DOMImplementation impl = builder.getDOMImplementation();
        Document xmldoc = impl.createDocument(null, "TODOs", null);

        Element root = xmldoc.getDocumentElement();
        Element e0 = xmldoc.createElement("TOPIC");
        Element e1 = xmldoc.createElement("TITLE");
        Node n1 = xmldoc.createTextNode("Java");
        e1.appendChild(n1);

        Element e2 = xmldoc.createElement("URL");
        Node n2 = xmldoc.createTextNode("http://www.server.com");
        e2.appendChild(n2);
        e0.appendChild(e1);
        e0.appendChild(e2);
        root.appendChild(e0);

        Node pi = xmldoc.createProcessingInstruction("xml-stylesheet", "type=\"text/xsl\" href=\"TODOs.xsl\"");
        xmldoc.insertBefore(pi, root);

        StreamResult out = new StreamResult("howto.xml");
        DOMSource domSource = new DOMSource(xmldoc);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.transform(domSource, out);
    }
}