XML Processing using SAX Parser

SAXTest.java
~~~~~~~~~~~~
package com.anil;

import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;
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;

/**
* Simple XML process use SAX method, SAX simple API for XML
*
*/
public class SAXTest extends DefaultHandler {
@Override
public void startDocument() throws SAXException {
   super.startDocument();
}

@Override
public void endDocument() throws SAXException {
   super.endDocument();
}

@Override
public void startElement(String uri, String localName, String name,
    Attributes attributes) throws SAXException {
   System.out.println("uri: " + uri);
   System.out.println("localName: " + localName);
   System.out.println("name: " + name);
   for (int i = 0; i < attributes.getLength(); i++) {
    System.out.println(i + " attributes: " + attributes.getValue(i));
   }
   if ("display".equals(name)) {
    String value = attributes.getValue("size");
    System.out.println(value);
   }
   if ("ram".equals(name)) {
    String value = attributes.getValue("type");
    System.out.println(value);
   }
}

@Override
public void endElement(String uri, String localName, String name)
    throws SAXException {
   super.endElement(uri, localName, name);
}

// SAX simple API for XML
public static void main(String[] args) {
   try {
    /*
    * get SAXParser then parse XML file
    */
    SAXParserFactory parserFactory = SAXParserFactory.newInstance();
    SAXParser parser = parserFactory.newSAXParser();
    parser.parse("anil.xml", new SAXTest());

   } catch (ParserConfigurationException e) {
    e.printStackTrace();
   } catch (SAXException e) {
    e.printStackTrace();
   } catch (IOException e) {
    e.printStackTrace();
   }
}

}
--------------------------------------------------------------------------------------------------------------
anil.xml
~~~~~~~~
 <?xml version="1.0" encoding="utf-8"?>
<computer>
<display size="17">Samsung</display>
<box>
   <motherboard>
    <cpu>E8300</cpu>
    <ram type="DDR2">2G</ram>
    <displaycard>nVidia</displaycard>
   </motherboard>
   <harddisk>320G</harddisk>
   <dvdrom>16X</dvdrom>
</box>
</computer>




No comments:

Post a Comment