Home Tutorial Xml Jdom JDOM example in java, How to read a xml file in java.

 
 

JDOM example in java, How to read a xml file in java.
Posted on: August 18, 2010 at 12:00 AM
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

Related Tags for JDOM example in java, How to read a xml file in java.:


Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.