Tuesday, April 2, 2013

Using JDOM API to create an XML document

JDOM is an open source library for working with a Java representation of an XML document. JDOM provides a way to represent that document for easy and efficient reading, manipulation, and writing. It has a straightforward API, is a lightweight and fast, and is optimized for the Java programmer.
More info about JDOM


As we know JDOM is a very useful library to provide a complete , java based solution for accessing, manipulating , and outputting XML data from java code.

The following example simply describes how to create an XML file by using JDOM library.

package com.app;
import java.io.FileWriter;
import java.io.IOException;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
public class JDOMXml { public static void main(String[] args) { Element note = new Element("note");
Document document = new Document();
document.setRootElement(note);
Element to = new Element("to"); to.setText("Unknown");
document.getRootElement().addContent(to);
Element from = new Element("from");
from.setText("Pradeep");
document.getRootElement().addContent(from);
Element heading = new Element("heading");
heading.setText("Heading");
document.getRootElement().addContent(heading);
Element message = new Element("message");
message.setText("Urgent message");
document.getRootElement().addContent(message);
XMLOutputter outputter = new XMLOutputter();
outputter.setFormat(Format.getPrettyFormat());
try {
outputter.output(document, new FileWriter("F:\\file.xml"));
System.out.println("Successfully create xml file.");
} catch (IOException e) {
System.out.println("Couldn't created xml file." + e.getMessage());
}
}
}

After running above programme it produces following outkput.


<?xml version="1.0" encoding="UTF-8"?>
<note>
  <to>Unknown</to>
  <from>Pradeep</from>
  <heading>Heading</heading>
  <message>Urgent message</message>
</note>