Create new XML file using DOM in Java

In the previous tutorial, we learned about how to read an XML file using the DOM in Java. In this tutorial, we will learn how to create new XML file using DOM!

The steps for creating a new XML file using the DOM include:

  • Use the DocumentBuilder object to define the contents of the XML file
  • Use Transformer object to write XML file to disk.

In this tutorial, we will go into the detail example to create XML file with the following content:



Definition of XML file content

We will first create a new Document object from the DocumentBuilder object.

In the XML file above, the <students> tag is the outermost tag, root element. So we’ll add this tag first.

Now we will add the <student> tag inside the <students> tag:

To add the n0=”1″ attribute to the <student> tag, we will use the Attr object:

Inside the <student> tag, we have more <name>, <code> and <age> tags, so our remaining task is to create 3 Elements for those 3 tags and add them to the <student> tag.

Name tag:

Code tag:

Age tag:



Burn the XML file to disk

By using the Transformer object, we will write the contents of the file to the drive where we specify it.

First we need Transformer object before:

In the Transformer object, it has a method called transform() with two parameters: the Source interface (created from the Document object containing the contents of the XML file) and the Interface Result (which contains information about the file XML after writing to the drive) to write XML file to the drive.

We will create the DOMSource object (this object implements the Source interface) to contain the contents of the file:

And the StreamResult object (the implementation of the Result Interface) contains the information of the XML file:

Now we can call the Transformer object’s transform() method to write the contents of the file to disk:

Full code as follows:

Result:

Create new XML file using DOM in Java

One thought on “Create new XML file using DOM in Java

  1. Hello, i want to read xml file usind dom parser which containing firstname and lastname nodes then write output.xml file which have just one node ===> firstname =the values for ( firstname+lastname) .

    input.xml
    firstname : Jan
    lastname : kruz

    output.xml
    fistname : jan kurz

    how can i do it?

Add Comment