Create XML Document

Java JDOM Parser is a Java API that has classes and methods to create XML documents from scratch. We can create a new JDOM document object and add elements, attributes using the methods available in Document and Element interfaces. In this chapter, we are going to use setRootElement(), addContent(), setText() and setAttribute() methods to create XML files in detail.

Create XML using Java JDOM parser

We can create an XML document in Java using JDOM parser through following steps −

  • Step 1: Creating JDOM Document object
  • Step 2: Creating and appending Root Element
  • Step 3: Creating elements and attributes
  • Step 4: Appending Elements to Root
  • Step 5: Writing the content into XML file
  • Step 6: Testing the output using console

Step 1: Creating JDOM Document object

The org.jdom2 package has Document class. It represents the XML document. This class has methods to access the root element and also the document level information. We create a new document as follows −

Document doc =newDocument();

Step 2: Creating and appending Root Element

An XML document must contain a root element. We create root element using Element class of org.jdom2 package. If we provide a String to the constructor, it creates element with that supplied local name.

The setRootElement() method in the Document class sets the root of the document. This method takes Element as an argument and sets it as the root. If the root element is already present, the old root Element gets replaced with this supplied Element.

ElementRootElement=newElement("root");
doc.setRootElement(RootElement);

Step 3: Creating elements and attributes

We can create Elements the same way we created root element in the previous step. To set an attribute to the Element, we use setAttribute() method as follows −

Element newElement =newElement("FirstElement");
newElement.setAttribute("attr_name","attr_value");

Step 4: Appending Elements to Root

The Elements created in the previous step are now attached to the root element using addContent() method. This method takes single element or collection of elements in the form of content list and adds them to the element accordingly.

RootElement.addContent(newElement);

Step 5: Writing the content into XML file

The TransformerFactory class is used to create a new instance of Transformer object. Using the transform() function in Transformer class, source is transformed to the destination result. We are creating JDOMSource object by passing document as a parameter. This JDOMSource object is transformed into StreamResult as follows −

TransformerFactory transformerFactory =TransformerFactory.newInstance();Transformer transformer = transformerFactory.newTransformer();JDOMSource source =newJDOMSource(doc);StreamResult result =newStreamResult(newFile("newFile.xml"));
transformer.transform(source, result);

Step 6: Testing the output using console

This is an optional step used for testing purpose. To print the output on the console, an XMLOutputter object is created and the Document object is passed as follows −

XMLOutputter xmlOutput =newXMLOutputter();
xmlOutput.setFormat(Format.getPrettyFormat());
xmlOutput.output(doc,System.out);

Creating Simple XML File

Using, the above mentioned steps, let us create a simple XML file that has root element alone. A new document object is created and the Root element is attached using setRootElement() method.

The setText() method of Element object takes the text content in the form of a String and attaches it to the Element.

Example

Here is the XML file we need to create. It has a root element named “cars” and the text content, “Ferrari”.

<cars>Ferrari</cars>

The following CreateXMLFile.java creates the XML file and stores it in D drive with the file name as “cars.xml”.

importjava.io.File;importjavax.xml.transform.Transformer;importjavax.xml.transform.TransformerFactory;importjavax.xml.transform.stream.StreamResult;importorg.jdom2.Document;importorg.jdom2.Element;importorg.jdom2.output.Format;importorg.jdom2.output.XMLOutputter;importorg.jdom2.transform.JDOMSource;publicclassCreateXMLFile{publicstaticvoidmain(String[] args){try{//Creating JDOM Document objectDocument doc =newDocument();//Creating and appending Root ElementElement carsElement =newElement("cars");
         carsElement.setText("Ferrari");
         doc.setRootElement(carsElement);//writing the content into XML fileTransformerFactory transformerFactory =TransformerFactory.newInstance();Transformer transformer = transformerFactory.newTransformer();JDOMSource source =newJDOMSource(doc);StreamResult result =newStreamResult(newFile("D:\\cars.xml"));
         transformer.transform(source, result);//Output to console for testingXMLOutputter xmlOutput =newXMLOutputter();
         xmlOutput.setFormat(Format.getPrettyFormat());
         xmlOutput.output(doc,System.out);}catch(Exception e){
         e.printStackTrace();}}}

For testing purpose, we have printed the content of XML document on the console.

<?xml version="1.0" encoding="UTF-8"?>
<cars>Ferrari</cars>

Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

Creating Attributes

Let us now add child elements to the root Element. Also, let us add attributes to our elements. In this example, we see how to create elements along with their attributes and attach them to the root. The setAttribute() method on each element sets the attribute and setText() method is used to set the text content of each element.

Example

Here is the cars.xml file that we need to create −

<cars><supercars company="Ferrari"><carname type="formula one">Ferrari 101</carname><carname type="sports">Ferrari 202</carname></supercars></cars>

The following CreateAttributes.java program creates the cars.xml file in D drive.

importjava.io.File;importjavax.xml.transform.Transformer;importjavax.xml.transform.TransformerFactory;importjavax.xml.transform.stream.StreamResult;importorg.jdom2.Attribute;importorg.jdom2.Document;importorg.jdom2.Element;importorg.jdom2.output.Format;importorg.jdom2.output.XMLOutputter;importorg.jdom2.transform.JDOMSource;publicclassCreateAttributes{publicstaticvoidmain(String[] args){try{//Creating JDOM Document objectDocument doc =newDocument();//Creating and appending Root ElementElement carsElement =newElement("cars");
         doc.setRootElement(carsElement);//Creating elements and attributesElement supercarElement =newElement("supercars");
         supercarElement.setAttribute("company","Ferrari");Element carElement1 =newElement("carname");
         carElement1.setAttribute("type","formula one");
         carElement1.setText("Ferrari 101");Element carElement2 =newElement("carname");
         carElement2.setAttribute("type","sports");
         carElement2.setText("Ferrari 202");

         supercarElement.addContent(carElement1);
         supercarElement.addContent(carElement2);//Appending Elements to Root
         carsElement.addContent(supercarElement);//writing the content into XML fileTransformerFactory transformerFactory =TransformerFactory.newInstance();Transformer transformer = transformerFactory.newTransformer();JDOMSource source =newJDOMSource(doc);StreamResult result =newStreamResult(newFile("D:\\Jdomcars.xml"));
         transformer.transform(source, result);//Output to console for testingXMLOutputter xmlOutput =newXMLOutputter();
         xmlOutput.setFormat(Format.getPrettyFormat());
         xmlOutput.output(doc,System.out);}catch(Exception e){
         e.printStackTrace();}}}

The output window displays the file content as follows −

<?xml version="1.0" encoding="UTF-8"?>
<cars>
  <supercars company="Ferrari">
    <carname type="formula one">Ferrari 101</carname>
    <carname type="sports">Ferrari 202</carname>
  </supercars>
</cars>

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *