Saturday, December 31, 2011

XML parsing in java example using JDOM


JDOM provides a very straightforward mechanism of parsing an XML file. JDOM does not itself include a parser. Instead it depends on a SAX parser to parse documents and build JDOM models from them. Once, the model document is built, the any element can be easily accessed through appropriate methods.

The following sample code parses the file "Personnel.xml" and produces the console output as shown below :

# Personnel.xml

<?xml version="1.0" encoding="UTF-8"?>
<Personnel>
    <Employee type="permanent" id="p124">
         <Name>Manoj Shrestha</Name>
         <Age>25</Age>
         <Address><![CDATA[Tokyo - Shinjuku 1-152-21-533]]></Address>
    </Employee>
    <Employee type="contract" id="c230">
         <Name>Lionel Messi</Name>
         <Age>24</Age>
         <Address><![CDATA[Barcelona 444-23]]></Address>
    </Employee>
</Personnel>

Source Code :


package com.manoj.examples.xml;

import java.io.IOException;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

/**
 * The Class XMLParserJDOM.
 * @author Manoj Shrestha
 * @Contact m.javaprogrammer@gmail.com
 */
public class XMLParserJDOM {
      public static void main(String[] args) {
            try {
                  // The file name is relative to the main project folder
                  Document document = new SAXBuilder().build("Personnel.xml");
                  Element rootElement = document.getRootElement();

                  System.out.println("Root Element : " + rootElement.getName());
                  System.out.println();

                  List<Element> employeeList = rootElement.getChildren("Employee");
                  for (Element employee : employeeList) {
                        System.out.print("Employee Details : ");
                        System.out.print(" Id = " + employee.getAttributeValue("id"));
                        System.out.print(" Type = " + employee.getAttributeValue("type"));
                        System.out.print(" Name = " + employee.getChild("Name").getText());
                        System.out.print(" Age = " + employee.getChild("Age").getText());
                        System.out.println(" Address = " 
                                + employee.getChild("Address").getText());
                  }
            } catch (JDOMException e) {
                  e.printStackTrace();
            } catch (IOException e) {
                  e.printStackTrace();
            }
      }
}



# The console output :


Root Element : Personnel

Employee Details :  Id = p124 Type = permanent Name = Manoj Shrestha Age = 25 Address = Tokyo - Shinjuku 1-152-21-533
Employee Details :  Id = c230 Type = contract Name = Lionel Messi Age = 24 Address = Barcelona 444-23










No comments :

Post a Comment