java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to create a Document object?

The following example show you how to create a simple Document object in JDOM. We can create a new document directly by creating a new instance of the Document class, for additional information we can pass an Element as an argument.

To create a Document from an existing XML file we can use the SAXBuilder. Beside reading from file we can also build a Document from stream and URL.

package com.javacoderanch.example.jdom;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;


public class JDOMCreateDocument {
    public static void main(String[] args) {
        // Creating a document with an Element as the parameter.
        Element element = new Element("root");
        element.setText("Hello World");
        Document document = new Document(element);
        System.out.println("root.getName() = " +

        // We can also create a document from a file, stream or URL using
        // a SAXBuilder
        SAXBuilder builder = new SAXBuilder();
        try {
            // Build a document from a file using a SAXBuilder.
            // The content of data.xml file:
            // <data>
            //     <row>
            //         <username>alice</username>
            //         <password>secret</password>
            //     </row>
            // </data>
            document = File("data.xml"));
            Element root = document.getRootElement();
            System.out.println("root.getName() = " + root.getName());
        } catch (JDOMException e) {
        } catch (IOException e) {