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>
Latest posts by Wayan (see all)
- How do I handle cookies using Jakarta Servlet API? - April 19, 2025
- How do I set response headers with HttpServletResponse? - April 18, 2025
- How do I apply gain and balance using FloatControl? - April 18, 2025