Showing posts with label Java XML Parsing. Show all posts
Showing posts with label Java XML Parsing. Show all posts

Tuesday, June 14, 2011

How to Parse XML using Java

Step 2- SAX Parser XML is Same

package org.best.example;
 
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
 
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
 
public class ReadXMLFileSAX {
 
 public static void main(String argv[]) {
 
  try {
 
     SAXParserFactory factory = SAXParserFactory.newInstance();
     SAXParser saxParser = factory.newSAXParser();
 
     DefaultHandler handler = new DefaultHandler() {
 
     boolean bfname = false;
     boolean blname = false;
     boolean bnname = false;
     boolean bsalary = false;
 
     public void startElement(String uri, String localName,
        String qName, Attributes attributes)
        throws SAXException {
 
        System.out.println("Start Element :" + qName);
 
        if (qName.equalsIgnoreCase("FIRSTNAME")) {
           bfname = true;
        }
 
        if (qName.equalsIgnoreCase("LASTNAME")) {
           blname = true;
        }
 
        if (qName.equalsIgnoreCase("NICKNAME")) {
           bnname = true;
        }
 
        if (qName.equalsIgnoreCase("SALARY")) {
           bsalary = true;
        }
 
     }
 
     public void endElement(String uri, String localName,
          String qName)
          throws SAXException {
 
          System.out.println("End Element :" + qName);
 
     }
 
     public void characters(char ch[], int start, int length)
         throws SAXException {
 
         if (bfname) {
            System.out.println("First Name : "
                + new String(ch, start, length));
            bfname = false;
          }
 
          if (blname) {
              System.out.println("Last Name : "
                  + new String(ch, start, length));
              blname = false;
           }
 
          if (bnname) {
              System.out.println("Nick Name : "
                  + new String(ch, start, length));
              bnname = false;
           }
 
          if (bsalary) {
              System.out.println("Salary : "
                  + new String(ch, start, length));
              bsalary = false;
           }
 
        }
 
      };
 
      saxParser.parse("c:\\file.xml", handler);
 
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
 
}

Monday, June 13, 2011

How to Parse XML using Java

Step 2: Dom Parser
 
package org.best.example;
 
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;
 
public class ReadXMLFile {
 
 public static void main(String argv[]) {
 
 try {
 
    File fXmlFile = new File("c:\\file.xml");
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(fXmlFile);
    doc.getDocumentElement().normalize();
 
    System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
    NodeList nList = doc.getElementsByTagName("staff");
    System.out.println("-----------------------");
 
    for (int temp = 0; temp < nList.getLength(); temp++) {
 
       Node nNode = nList.item(temp);     
       if (nNode.getNodeType() == Node.ELEMENT_NODE) {
 
          Element eElement = (Element) nNode;
 
          System.out.println("First Name : "  + getTagValue("firstname",eElement));
          System.out.println("Last Name : "  + getTagValue("lastname",eElement));
          System.out.println("Nick Name : "  + getTagValue("nickname",eElement));
          System.out.println("Salary : "  + getTagValue("salary",eElement));
 
        }
    }
  } catch (Exception e) {
    e.printStackTrace();
  }
 }
 
 private static String getTagValue(String sTag, Element eElement){
    NodeList nlList= eElement.getElementsByTagName(sTag).item(0).getChildNodes();
    Node nValue = (Node) nlList.item(0); 
 
    return nValue.getNodeValue();    
 }
 
}

Sunday, June 12, 2011

How to Parse XML using Java


Step1:- Parsing XML

if you are a beginner to XML using Java then this is the perfect sample to parse a XML file create Java Objects and manipulate them.

The idea here is to parse the staff.xml file with content as below



<?xml version="1.0"?>
<company>
 <staff>
  <firstname>Amit</firstname>
  <lastname>Mangal</lastname>
  <nickname>Tiger</nickname>
  <salary>100000</salary>
 </staff>
 <staff>
  <firstname>Lalit</firstname>
  <lastname>Aggarwal</lastname>
  <nickname>Lalit</nickname>
  <salary>200000</salary>
 </staff>
</company>

From the parsed content create a list of Staff objects and print it to the console. The output would be something like

Root element :company
-----------------------
First Name : Amit
Last Name : Mangal
Nick Name : Tiger
Salary : 100000
First Name : Lalit
Last Name : Aggarwal
Nick Name : Lalit
Salary : 200000

We will start with a DOM parser to parse the xml file, create Employee value objects and add them to a list. To ensure we parsed the file correctly let's iterate through the list and print the employees data to the console.