Last Updated:

Creating an XML File and Writing with JDOM - Java

JDOM provides many methods for easily writing data to XML, working with elements and attributes. To do this, a special class is used that can be used to write a document to any OutputStream or Writer object.XMLOutputter

In our example, we're using maven, so we'll just add the following code to the dependency:pom.xml

Let's move on to practice, where we will create a list of Student objects, and then write it to an XML file.

The Student class is as follows:

We'll also set the id attribute to each Student element and add a namespace for the root element:

Note that we immediately wrote the data to an XML file. If you want to view the data before writing, add the following lines to output the generated JDOM document to the console:

It should also be noted that we set a namespace for each new Student element. If you remove the explicit namespace statement for each non-root element with the following:

to this:

then in the output XML file, the namespace will be empty:

The result of writing to an XML file using JDOM: