Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.io.StringWriter;

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

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

        DocumentBuilder loader = factory.newDocumentBuilder();
        Document document = loader.newDocument();
        edit(document);

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

    }

    public static void edit(Document document) {
        String docNS = "http://www.my-company.com";

        Element order = document.createElementNS(docNS, "order");
        document.appendChild(order);
        order.setAttribute("xmlns", docNS);
    }

    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;
    }
}