Wednesday, May 16, 2012

Xml parsing using jdom in java

<?xml version="1.0"?>
<company>
 <staff>
  <firstname>yong</firstname>
  <lastname>mook kim</lastname>
  <nickname>mkyong</nickname>
  <salary>100000</salary>
 </staff>
 <staff>
  <firstname>low</firstname>
  <lastname>yin fong</lastname>
  <nickname>fong fong</nickname>
  <salary>200000</salary>
 </staff>
</company>

3. Java File

Use JDOM parser to parse above XML file.
import java.io.File;
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;
 
public class ReadXMLFile {
 public static void main(String[] args) {
 
   SAXBuilder builder = new SAXBuilder();
   File xmlFile = new File("c:\\file.xml");
 
   try {
 
  Document document = (Document) builder.build(xmlFile);
  Element rootNode = document.getRootElement();
  List list = rootNode.getChildren("staff");
 
  for (int i = 0; i < list.size(); i++) {
 
     Element node = (Element) list.get(i);
 
     System.out.println("First Name : " + node.getChildText("firstname"));
     System.out.println("Last Name : " + node.getChildText("lastname"));
     System.out.println("Nick Name : " + node.getChildText("nickname"));
     System.out.println("Salary : " + node.getChildText("salary"));
 
  }
 
   } catch (IOException io) {
  System.out.println(io.getMessage());
   } catch (JDOMException jdomex) {
  System.out.println(jdomex.getMessage());
   }
 }
}
Output
First Name : yong
Last Name : mook kim
Nick Name : mkyong
Salary : 100000
First Name : low
Last Name : yin fong
Nick Name : fong fong
Salary : 200000

No comments:

Post a Comment