Java sax example
htwww//:spt.theitroad.com
Here's an example of how to use the Simple API for XML (SAX) in Java to parse an XML document:
Suppose you have the following XML document example.xml
:
<?xml version="1.0"?> <catalog> <book id="bk101"> <author>Gambardella, Matthew</author> <title>XML Developer's Guide</title> <genre>Computer</genre> <price>44.95</price> <publish_date>2000-10-01</publish_date> <description>An in-depth look at creating applications with XML.</description> </book> <book id="bk102"> <author>Ralls, Kim</author> <title>Midnight Rain</title> <genre>Fantasy</genre> <price>5.95</price> <publish_date>2000-12-16</publish_date> <description>A former architect battles corporate zombies, an evil sorceress, and her own childhood to become queen of the world.</description> </book> </catalog>
Here's an example of how to parse this document using the SAX API in Java:
import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import java.io.File; public class MyHandler extends DefaultHandler { private boolean author = false; private boolean title = false; private boolean genre = false; private boolean price = false; private boolean publishDate = false; private boolean description = false; public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (qName.equalsIgnoreCase("author")) { author = true; } else if (qName.equalsIgnoreCase("title")) { title = true; } else if (qName.equalsIgnoreCase("genre")) { genre = true; } else if (qName.equalsIgnoreCase("price")) { price = true; } else if (qName.equalsIgnoreCase("publish_date")) { publishDate = true; } else if (qName.equalsIgnoreCase("description")) { description = true; } } public void endElement(String uri, String localName, String qName) throws SAXException { // Do nothing } public void characters(char ch[], int start, int length) throws SAXException { if (author) { System.out.println("Author: " + new String(ch, start, length)); author = false; } else if (title) { System.out.println("Title: " + new String(ch, start, length)); title = false; } else if (genre) { System.out.println("Genre: " + new String(ch, start, length)); genre = false; } else if (price) { System.out.println("Price: " + new String(ch, start, length)); price = false; } else if (publishDate) { System.out.println("Publish Date: " + new String(ch, start, length)); publishDate = false; } else if (description) { System.out.println("Description: " + new String(ch, start, length)); description = false; } } } public class MySaxParser { public static void main(String[] args) throws Exception { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); MyHandler handler = new MyHandler