Monday, July 16, 2012

Read XML File Using Java

1) Save Xml file name :bookstore.xml in C dirve

<bookstore>
<book>
<title>Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book>
<title >Harry Ptter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book>
<title>Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>

2) Read above bookstore.xml using java code. BookStore.java


import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;


/**
 *
 */

/**
 * @author Administrator
 *
 */
public class BookStore {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub


try {
File bookXml = new File("C:\\bookstore.xml");

DocumentBuilderFactory docBuildFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuildFactory.newDocumentBuilder();
Document doc = docBuilder.parse(bookXml);
doc.getDocumentElement().normalize();

System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nodeList = doc.getElementsByTagName("book");
System.out.println("-----------------------\n");

for (int temp = 0; temp < nodeList.getLength(); temp++) {

  Node nodeNode = nodeList.item(temp);
  if (nodeNode.getNodeType() == Node.ELEMENT_NODE) {

     Element eElement = (Element) nodeNode;

     System.out.println("Title : " + getTagValue("title", eElement));
     System.out.println("Author : " + getTagValue("author", eElement));
         System.out.println("Year : " + getTagValue("year", eElement));
     System.out.println("Price : " + getTagValue("price", eElement));
     System.out.println("\n\n");
  }
}
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
private static String getTagValue(String strTag, Element eElement) {
NodeList nodeList = eElement.getElementsByTagName(strTag).item(0).getChildNodes();

   Node nodeValue = (Node) nodeList.item(0);

return nodeValue.getNodeValue();
 }
}


Below is the out put:

Root element :bookstore
-----------------------

Title : Everyday Italian
Author : Giada De Laurentiis
Year : 2005
Price : 30.00



Title : Harry Ptter
Author : J K. Rowling
Year : 2005
Price : 29.99



Title : Learning XML
Author : Erik T. Ray
Year : 2003
Price : 39.95



Everyday Italian