Read XML using Java

Ads
 

Read XML using Java

Hi All,

Good Morning, I have been working as a Manual Test engineer for last 4 years. Now i started learning java for automating some of the functionaries. And here goes my requirements.

Read huge complex xml and compare values with DB2 database and generate a report. So First of all i need to read xml using java . i did good research in google and came to know that there are many ways to read using different API like SAX, DOM , XOM Jar, XML Beans Jar and so on...

So i request you all to suggest best way to read XML ie SAX or Dom ? if possible sample code also.

WebTester.

View Answers

April 30, 2012 at 1:57 PM

import java.io.*;
import java.util.*;
import org.w3c.dom.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

public class ParseXmlFile{

 public static void main(String argv[]){
 ArrayList<Student> list=new ArrayList<Student>();
  try{
  File file = new File("c:\\file.xml");
  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  DocumentBuilder db = dbf.newDocumentBuilder();
  Document document = db.parse(file);
  document.getDocumentElement().normalize();
  System.out.println("Root element "+ document.getDocumentElement().getNodeName());
  NodeList node = document.getElementsByTagName("student");
  System.out.println("Information of the students");

  for(int i = 0; i < node.getLength(); i++){
  Node firstNode = node.item(i);
  if(firstNode.getNodeType()== Node.ELEMENT_NODE){
  Element element = (Element) firstNode;
  NodeList firstNameElemntList = element.getElementsByTagName("name");
  Element firstNameElement = (Element) firstNameElemntList.item(0);
  NodeList firstName = firstNameElement.getChildNodes();
  Node n1=firstName.item(0);
  String name=n1.getNodeValue();

  NodeList lastNameElementList = element.getElementsByTagName("address");
  Element lastNameElement = (Element)lastNameElementList.item(0);
  NodeList lastName = lastNameElement.getChildNodes();
  Node n2=lastName.item(0);
  String address=n2.getNodeValue();
  list.add(new Student(name,address));
  }
  }
  for(Student st:list){
  System.out.println(st.getName()+"\t"+st.getAddress());
  }
  }
  catch (Exception e) {
  e.printStackTrace();
  }
 }
}

April 30, 2012 at 1:58 PM

Parse XML using JDOM

import java.io.*;
import org.jdom.*;
import java.util.*;
import org.jdom.input.SAXBuilder;

public class ReadXMLUsingJDOM {
  public static void main(String[] args) {
      SAXBuilder builder = new SAXBuilder();
      File xmlFile = new File("c:\\student.xml");

      try {

        Document document = (Document) builder.build(xmlFile);
        Element rootNode = document.getRootElement();
        List list = rootNode.getChildren("class");

        for (int i = 0; i < list.size(); i++) {

           Element node = (Element) list.get(i);
           String classid = node.getAttribute("id").getValue();
           String name = node.getChildText("Name");
           System.out.println("Class ID: "+classid);
           System.out.println("Name: "+name);

           List list1 = node.getChildren("Student");
            for (int j = 0; j < list1.size(); j++) {
            Element node1 = (Element) list1.get(j);
            String sid = node1.getAttribute("id").getValue();
            String sname = node1.getChildText("Name");
            System.out.println("Student ID: "+sid);
            System.out.println("Student Name: "+sname);
            List list2 = node1.getChildren("Address");
            for (int k = 0; k < list2.size(); k++) {
               Element node2 = (Element) list2.get(k);
               String saddress = node2.getChildText("id");
               System.out.println("Address: "+saddress);
               }
            }
         }
      }
    catch(Exception e){
      System.out.println("Execption " + e.getMessage());
    }
  }
}

May 1, 2012 at 11:36 AM

Thanks a lot for the quick reply.

From above two codes i think reading xml using JDOM is simple. But my XML size ranges from 30 MB to 60 MB. Will JDOM handle such huge load ?

Thanks in advance


May 1, 2012 at 8:33 PM

Finally i decided to use JDOM . i am using following xml <Root> <Maste-item-detail coder="afrffica"> Name1 description description2

<Maste-item-detail coder="afrffica"> name2 description description2 <Maste-item-detail coder="afrffica"> name3 description description2

And my java code is here SAXBuilder builder = new SAXBuilder(); File xmlFile = new File("H:\sample1.xml");

  try {
    Document document = (Document) builder.build(xmlFile);

    Element rootNode = document.getRootElement();
    System.out.println ("Root element of the doc is " + rootNode.getName());
    List MasterItemlist = rootNode.getChildren("Maste-item-detail");

    System.out.println("Total Single Items : " + MasterItemlist.size());
    for (int i = 0; i < MasterItemlist.size(); i++) {

       Element node = (Element) MasterItemlist.get(i);
       Element innernode = (Element) node.getChildren("content");
       List name = innernode.getChildren("name");
       System.out.println("First Name : " + innernode.getChildText("name"));

    }

and i am getting following error Exception in thread "main" java.lang.ClassCastException: org.jdom.ContentList$FilterList cannot be cast to org.jdom.Element at ReadXMLFile.main(ReadXMLFile.java:28) Root element of the doc is Root Total Single Items : 3

please help me to get it right

Ads









Related Tutorials/Questions & Answers:
Read XML using Java
of all i need to read xml using java . i did good research in google and came to know...Read XML using Java  Hi All, Good Morning, I have been working.../xmlParsing/java-xml-parsing-using-sax.shtml http://www.roseindia.net/xml/sax
read xml using java
read xml using java  <p>to read multiple attributes and elements from xml in an order.... ex :component name="csl"\layerinterfacefile="poo.c...;   Please visit the following link: Read XML data
Advertisements
how to read and write an xml file using java
how to read and write an xml file using java  Hi Can anyone help me how to read and write an xml file which has CData using java
How to read value from xml using java?
How to read value from xml using java?  Hi All, I want to read value from following xml using java.. In <Line>,data is in format of key and value pair.. i want to read only values..could u plz help me in this?Thanks
read XML file and display it using java servlets
read XML file and display it using java servlets  sir, i can't access Xml which is present in my d drive plz can u should go through my code n tell me the things where i went wrong java servlet program protected void
how to read values from java in xml?
how to read values from java in xml?  how to read values from java in xml
Read Complex XML using DOM/SAX Parser.
Read Complex XML using DOM/SAX Parser.  I have a XML file which is having two types of Items. I want to extract all details of a type only. My XML goes something like this <Movie> <Bollywood> <Actor> Shah Rukh
read xml elements
read xml elements  i want read xml data using sax parser in java. but is there any classes or methods to read xml elements
read xml elements
read xml elements  i want read xml data using sax parser in java. but is there any classes or methods to read xml elements
Read the value from XML in java
Read the value from XML in java  Hi, i have an XML with the following code. I need to get the path("D... the permissions on that file.So how can i read that value. This is little urgent
read/write to Windows Registry using Java
read/write to Windows Registry using Java  read/write to Windows Registry using Java
xml file reading using java
xml file reading using java  hi deepak I want to read some data from xml file and send that output to particular email address using java   import org.w3c.dom.*; import org.w3c.dom.Node; import javax.xml.parsers.
xml Converting to java using JDOM
xml Converting to java using JDOM  Hello , I am new to java and JDom so i make a Xml file and i need help to read it from java using objects , my... should be inside a student object i will include the java code and xml code and i
parsing xml file using java code
parsing xml file using java code  parsing a xml file using java code
How to values from xml using java?
How to values from xml using java?  Hi All, I want to read value from following < Line> xml using java.. In < Line>,data is in format of key and value pair.. i want to read only values..could u plz help me
read xml
read xml   hi all, i want to ask about how to read an xml in java ME.. here is the xml file <data> <value> <struct> <member> <name> User_Name
can't read my xml file in java
can't read my xml file in java  i've a xml file like this : <...(); } the codes can't read the xml file bcz i want to append the whole xml in my gui. seems the problems is all xml tag must be enum. can you suggest me how to read
can't read my xml file in java
can't read my xml file in java  i've a xml file like this : <...(); } the codes can't read the xml file bcz i want to append the whole xml in my gui. seems the problems is all xml tag must be enum. can you suggest me how to read
can't read my xml file in java
can't read my xml file in java  i've a xml file like this : <...(); } the codes can't read the xml file bcz i want to append the whole xml in my gui. seems the problems is all xml tag must be enum. can you suggest me how to read
can't read my xml file in java
can't read my xml file in java  i've a xml file like this : <...(); } the codes can't read the xml file bcz i want to append the whole xml in my gui. seems the problems is all xml tag must be enum. can you suggest me how to read
can't read my xml file in java
can't read my xml file in java  i've a xml file like this : <...(); } the codes can't read the xml file bcz i want to append the whole xml in my gui. seems the problems is all xml tag must be enum. can you suggest me how to read
can't read my xml file in java
can't read my xml file in java  i've a xml file like this : <...(); } the codes can't read the xml file bcz i want to append the whole xml in my gui. seems the problems is all xml tag must be enum. can you suggest me how to read
Interceptors Configuration using Java or XML
In this section, you will learn about how to configure interceptors using Java or XML
To read & write a excel file using the core java
To read & write a excel file using the core java  Hai, I'm new to JavaProgram.But now i need java program to read & write a excel file so, can anyone help me to learn the above mentioned topic(link for the portion
Read Email using Java Mail API - James
Read Email using Java Mail API - James   https://www.roseindia.net/javamail/send-mail.shtml From this sample, i understand that we need to pass user credentials for reading the email content. Is there any option to read all
Read Email using Java Mail API - James
Read Email using Java Mail API - James   https://www.roseindia.net/javamail/send-mail.shtml From this sample, i understand that we need to pass user credentials for reading the email content. Is there any option to read all
Read Email using Java Mail API - James
Read Email using Java Mail API - James   https://www.roseindia.net/javamail/send-mail.shtml From this sample, i understand that we need to pass user credentials for reading the email content. Is there any option to read all
Read Email using Java Mail API - James
Read Email using Java Mail API - James   https://www.roseindia.net/javamail/send-mail.shtml From this sample, i understand that we need to pass user credentials for reading the email content. Is there any option to read all
Read Header/Footer Margin size using Java
Read Header/Footer Margin size using Java  Hi, Is it possible to read the "Header from Top" and "Footer from bottom" properties of a MS word document in Java? I have been searching the web for hours now, POI's and several other
Read Header/Footer Margin size using Java
Read Header/Footer Margin size using Java  Hi, Is it possible to read the "Header from Top" and "Footer from bottom" properties of a MS word document in Java? I have been searching the web for hours now, POI's and several other
XML- SAX Parser using JAXP API
In the previous issue of Java Jazz Up you have read about XML technology. In this issue, you will learn how XML technology works with Java using different kinds of XML...XML- SAX Parser using JAXP API      

Ads