Share on Google+Share on Google+

JDOM example in java, How to read a xml file in java.

Advertisement
In this tutorial, you will see how to read a xml file in java.

JDOM example in java, How to read a xml file in java.

In this tutorial, we will see how to  read a xml file in java.

Code.

Student.xml

<?xml version="1.0"?>
<Student >
  <info id="1"  >
    <first name="bharat">bly </first>
      </info>
  <info  id="2">
    <first name="ankit" >lko</first>    
  </info>
  <info id="3" >
    <first name="bikrant">lko</first>
    </info>
</Student>

ReadXMl.java


import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.DOMBuilder;
import java.io.File;
import java.util.List;

public class ReadXML {
  public static void main(String[] args) {
    try {
      String data = "student.xml";
      File file = new File(data);
      DOMBuilder builder = new DOMBuilder(false);
      Document doc = builder.build(file);
      Element root = doc.getRootElement();
      System.out.println("Root" + root);
      List row = root.getChildren("info");
      for (int i = 0; i < row.size(); i++) {
        Element infoElenemt = (Elementrow.get(i);
        List column = infoElenemt.getChildren("first");
        for (int j = 0; j < column.size(); j++) {
          Element student = (Elementcolumn.get(j);
          String name = student.getAttribute("name").getValue();
          String value = student.getText();
          System.out.println("Student name = " + name);
          System.out.println("City = " + value);
        }
      }
    catch (Exception e) {
      System.out.println("Execption " + e.getMessage());
    }
  }
}

Output.

Root[Element: <Student/>]
Student name = bharat
City = bly

Student name = ankit
City = lko
Student name = bikrant
City = lko

Download this code

Advertisements

Advertisement

Posted on: August 18, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.