« Home | Algorithms Used in Garbage collection » | Lower Case to Uppre Case Conversion » | PRINTING THE NON-PRIMES » | PRIME FACTORS OF ALL NON-PRIMES BELOW 500 » | What is Garbage Collection & Why is Garbage Collec... » | Public static void main (String args[]) » | Delete and Update values in MySql Using Java » | Insert values into table Using Java » | Program to Retrive values from Mysql Using Java » | Java Mysql Connectivity » 

Tuesday, March 14, 2006 

XML Parser in Java

// Team 1
// XML Parser

package book;
import java.io.File;
import org.w3c.dom.Document;
import org.w3c.dom.*;
import java.util.*;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

class XMLParser
{
public Hashtable getBooks()
{
Hashtable listBooks= new Hashtable();;
try
{
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse (new File("e:/input.xml"));

// normalize text representation
doc.getDocumentElement ().normalize ();
NodeList totallistBooks = doc.getElementsByTagName("books");
int totalBooks = totallistBooks.getLength();


for(int s=0; s<totallistBooks.getLength() ; s++){


Node firstPersonNode = totallistBooks.item(s);
if(firstPersonNode.getNodeType() == Node.ELEMENT_NODE){


Element firstPersonElement = (Element)firstPersonNode;

//-------
NodeList firstNameList = firstPersonElement.getElementsByTagName("bookId");
Element firstNameElement = (Element)firstNameList.item(0);

NodeList textFNList = firstNameElement.getChildNodes();

NodeList lastNameList = firstPersonElement.getElementsByTagName("bookName");
Element lastNameElement = (Element)lastNameList.item(0);

NodeList textLNList = lastNameElement.getChildNodes();


//inserting into hashtable key value pairs

listBooks.put(((Node)textLNList.item(0)).getNodeValue().trim(),((Node)textFNList.item(0)).getNodeValue().trim());


}//end of if clause



}//end of for loop with s var




}
catch (SAXParseException err)
{
System.out.println ("** Parsing error" + ", line " + err.getLineNumber () + ", uri " + err.getSystemId ());
System.out.println(" " + err.getMessage ());

}
catch (SAXException e)
{
Exception x = e.getException ();
((x == null) ? e : x).printStackTrace ();

}
catch (Throwable t)
{
t.printStackTrace ();
}

return listBooks;
}
}

About me

  • I'm phanindra
  • From Hyderabad, Andhra Pradesh, India
  • An Alumini of JNTU Hyd into happening IT industry...
My profile

Visitors
Bloggeries Blog Directory BlogRankings.com singapore blog directory blog search directory
Google
 
Web conceptoftheday.blospot.com