Create Dom Document and root element - Java XML

Java examples for XML:DOM

Description

Create Dom Document and root element

Demo Code

// This program is free software; you can redistribute it and/or modify it
//package com.java2s;
import org.w3c.dom.*;

import javax.xml.parsers.*;

public class Main {
    public static void main(String[] argv) throws Exception {
        System.out.println(CreateDom());
    }// www. j  a va  2s.  c  om

    public static Document CreateDom() {
        Document newdoc = getDocumentBuilder().newDocument();
        //newdoc..PreserveWhitespace = true;
        Element childnode = newdoc.createElement("root");
        newdoc.appendChild(childnode);
        return newdoc;
    }

    static DocumentBuilder getDocumentBuilder() {
        DocumentBuilder documentBuilder = null;
        try {
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
                    .newInstance();
            documentBuilder = documentBuilderFactory.newDocumentBuilder();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return documentBuilder;
    }
}

Related Tutorials