How do I create a Document object in JDOM?

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 org.kodejava.jdom;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;

import java.io.File;

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() = " +
                document.getRootElement().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:
            //
            // <?xml version="1.0" encoding="UTF-8"?>
            // <data>
            //     <row>
            //         <username>alice</username>
            //         <password>secret</password>
            //     </row>
            // </data>
            document = builder.build(new File("data.xml"));
            Element root = document.getRootElement();
            System.out.println("root.getName() = " + root.getName());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Maven Dependencies

<dependency>
    <groupId>org.jdom</groupId>
    <artifactId>jdom2</artifactId>
    <version>2.0.6.1</version>
</dependency>

Maven Central

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.