JDOM Write XML File Example from Object

In last tutorial we learned basics of Java JDOM and how we can read XML file to Object. In this tutorial we will learn about JDOM Write XML File example.

JDOM Write XML File

JDOM Document provides methods to easily create elements and attributes. XMLOutputter class can be used to write the Document to any OutputStream or Writer object.

For this example, we will create a list of Employee object and then write it to XML file.

We will set Employee ID as attribute to Employee element and set the namespace for root element Employees.

When we run above JDOM Write XML File example program, we get following XML file.

Notice that Employee elements have empty namespace because we set the namespace for root element only. If you want same namespace for all the elements, you need to create them specifically by using the constructor with namespace argument.

Also check the use of Format class for pretty printing XML file. We can use it to output XML in compact and raw format also.

By admin

Leave a Reply

%d bloggers like this: