Thursday, December 5, 2013

XML processing in Java

XML and HTML are Markup Languages. However, they are different. XML is generally used to store and transport structured data while HTML is used to format and present the data. Today XML is the most common tool for data transmissions on the web. In XML file, you can define your own tags or elements starting from a root tag and then its children tags. Here is an example of an XML file:

xml file example


The root element is Books. Under the root element, there are two sub-elements or children elements Book.

This tutorial is designed for people who come to work with XML file in Java. After completing the tutorial, you will be able to create an XML document and save it to a file, read data from an XML file, and modify elements in the XML file by using JDOM library. With the JDOM libary, XML file can be easily created, read, and modified.

Create XML document and Save it to a file

To create an XML document, first you will use the Element class to create a root element object. Then create a document object by using the Document class to wrap the root object. A child element object can also be constructed by using the Element class and added to root element by using the addContent method. You can add many children to the root element. To save the XML document to a file, you will use the XMLOutputter class. The XMLOutputter class has a method called output that can be used to write the document to the file.  See the example code below:

public static void createXML(){
//create a root element
Element root=new Element("Books");
//construct the document object with the root
Document doc=new Document(new Element("Books"));
//create first child element
Element b1=new Element("Book");
b1.setAttribute("Title","C++ for beginners");
b1.addContent(new Element("Author").setText("Dara"));
b1.addContent(new Element("Year").setText("2011"));
//add the first child to the root
root.addContent(b1);

//create second child element
Element b2=new Element("Book");
b2.setAttribute("Title","Java for programmers");
b2.addContent(new Element("Author").setText("Dara"));
b2.addContent(new Element("Year").setText("2012"));
//add the second child to the root
root.addContent(b2);
//save the document
XMLOutputter outputter=new XMLOutputter();
outputter.setFormat(Format.getPrettyFormat());
try {
outputter.output(doc, new FileWriter("d:/books.xml"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

Read data from the XML file

Reading data from an XML file is a common task. This task can be accomplished easily by using JDOM. To read the data from the XML file, you will use SAXBuilder class to construct a document object from the XML file. After you have the document object, you can easily navigate through the document to access all its elements. Read the example code below:


public static void readXML(){
SAXBuilder builder=new SAXBuilder();
try {
//construct document object from the file books.xml
Document doc = (Document)builder.build(new File("d:/books.xml"));
//get the root element
Element root=doc.getRootElement();
//get all children of the root
List<Element> chs=root.getChildren();
for(Element e: chs){
System.out.println("Book:");
System.out.println("\t"+e.getChild("Author").getText());
System.out.println("\t"+e.getChild("Year").getText());
}

} catch (JDOMException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

Modify the data in the XML file

Before you can modify the data in the XML file, first you need to read the XML file in to a document object as you did in the previous section. Then you can add new children elements to the root, update data of an element, or delete an element from the document. After you complete the tasks, call the output method of the XMLOutputter class to save change to the file. Here is the example code.

public static void ModifyXML(){
SAXBuilder builder=new SAXBuilder();
try {
Document doc = (Document)builder.build(new File("d:/books.xml"));
Element root=doc.getRootElement();
//create third child element
Element b3=new Element("Book");
b3.setAttribute("Title","C# for beginners");
b3.addContent(new Element("Author").setText("Dara"));
b3.addContent(new Element("Year").setText("2013"));

//add the third child to the root
root.addContent(b3);

//Update the year of a book
List<Element> chs=root.getChildren();
for(Element e: chs){
Element ce=e.getChild("Year");
if(ce.getText().equals("2013")){
ce.setText("2010");
break;
}
}
//Remove a book that has the title "C# for beginners"
for(Element e: chs){
if(e.getAttribute("Title").getValue().endsWith("C# for beginners")){
root.removeContent(e);
break;
}

}

//save the document
XMLOutputter outputter=new XMLOutputter();
outputter.setFormat(Format.getPrettyFormat());
outputter.output(doc, new FileWriter("d:/books.xml"));

} catch (JDOMException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

6 comments:

  1. Question:
    - How different between Class and Method ?
    - How different between using XML and other DBMS software like SqlServer, Oracle, Mysql ?

    ReplyDelete
  2. A METHOD is a member of a class. Xml is a language that can be used to write structured data to xml file. It is a common file for transmission on the web.

    ReplyDelete
  3. Hi this is a very nice and informative blog. keep it up.
    Free download bca project

    ReplyDelete
  4. It has been 3 years since this post was written and it still feels like XML is a big part of java processing. custom essay writing service interns are currently learning the some basic java codes which they use on their daily task.

    ReplyDelete
  5. Alongside solid suite of center APIs, you have to know the correct linguistic structure and component of coding in Java to wind up distinctly fruitful Java Developer. java

    ReplyDelete
  6. You need to kill time, you'd have time to look these kids active. Refer to our website. Hope you get the most comfort.
    Thanks for sharing ! word cookies game | hill climb racing 2

    ReplyDelete