Read XML using Java

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









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
Read XML in java - XML
Read XML in java  Hi Deepak, I want to read a xml file which have only one element with multiple attributes with same tag name. here is my file... a solution.my java code is given below. import java.io.File; import
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 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
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 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
accessing xml using java
accessing xml using java  I need to retrieve some elements in xml file using java   Hi Friend, Please visit the following links:ADS_TO_REPLACE_1 http://www.roseindia.net/xml/Listingnode.shtml http://www.roseindia.net
XML parsing using Java - XML
XML parsing using Java  I'm trying to parse a big XML file in JAVA..." in element "MIRate"(THE XML code is below).once he enters coverage rate I need... for it skipping all the elements in Table 1. I'm usin using saxparser, startelement
read string - using loops in Java
read string - using loops in Java  Write a program to read a string composed of an unknown number of words, then count the number of words in the string, and Display the longest and shortest words, with first letter Uppercase
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
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
simple code to write an read and write the login detail to a xml file using javascript ( username and password )
simple code to write an read and write the login detail to a xml file using... to write and read the login details (username and password )into a xml file using javascript. (XML database
read/write to Windows Registry using Java
read/write to Windows Registry using Java  read/write to Windows Registry using Java
how to read this xml file - XML
how to read this xml file  i want to read this xml file using java(using struts2 or using jsp) and i want result as name=admin menu=user... read i have tried lot more , but i am not able to read this xml file
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
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
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
how to read file using InputStreamReader in java
how to read file using InputStreamReader in java  Hi, I want to learn to use the InputStreamReader class of Java and trying to read a text file with the class. how to read file using InputStreamReader in java? Thanks  
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
Using HSSF 3.5 to READ XLS - Java Beginners
Using HSSF 3.5 to READ XLS  I just dont seem to get this working. I have tried the examples here on this homepage but they are out of date for 3.5 since they are built on and older relese i cant get them to work. All i want
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      
Data read. - XML
Data read.  How to store or read data in XML from Struts.Plz give me example. Thanx
parsing xml file using java code
parsing xml file using java code  parsing a xml file using java code
XML- read Text Mode - Java Error in Windows - reg. - Java Beginners
XML- read Text Mode - Java Error in Windows - reg.  Dear All I'm creating the code as read the XML file in BufferedReader method. Here I pasted the code below:. (*) First read the XML file using FileInputStream
how to create xml schema from xml doc using java
how to create xml schema from xml doc using java  i want to create xml schema from xml document programatically using java... am using Netbeans IDE 7.0 i hav created the xml document for a table of data from Database... now i
Interceptors Configuration using Java or XML
In this section, you will learn about how to configure interceptors using Java or XML
Reading an XML document using JDOM
Reading an XML document using JDOM       This Example shows you how to Read an XML document..., it is a tree based Java api. JDOM represents an XML document as a tree composed
How to Split a large XML file using java?
How to Split a large XML file using java?  How can we split a 500MB Xml file?I know how to split xml file after reading the entire document in a file.Here we cannot load the entire file as it is a large file
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
Sending and receiving xml message using Java Program
Sending and receiving xml message using Java Program  Hi Friends, I want to send and receive xml files between two java programs using wire format, could you suggest me the steps to be followed to acheive it or suggest some
Sending and receiving xml message using Java Program
Sending and receiving xml message using Java Program  Hi Friends, I want to send and receive xml files between two java programs using wire format, could you suggest me the steps to be followed to acheive it or suggest some
HOW TO SAVE XML INTO MYSQL AND RETRIEVE IT USING JAVA
HOW TO SAVE XML INTO MYSQL AND RETRIEVE IT USING JAVA  H ello, i have an xml code, i need to save it into mysql 5.5 server database using java. i... as xml and retrieve it the same way i saved it. SOMEONE PLEASE HELP.... this is my
JDOM example in java, 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 >
XML to DB2 Comparison using Java xpath
XML to DB2 Comparison using Java xpath  Hi , I am a manual tester...' products . i want to compare these xml values with db2 using Java. I have Good knowledge in C, C++ and Ok with java. I am planning to use xpath to get details
How to read yahoo mail using java mail api - WebSevices
How to read yahoo mail using java mail api  Hi there .... i wanted to know how to read mail from yahoo using pure java code. Is there any one who can help me regarding this, please if possible show me the exact way as well

Ads