I have started learning XML parsing in Java (currently reading Java & XML by Brett McLaughlin). Here is my first program to parse XML using SAX parser. Please review the code and let me know if that is correct way of parsing books.xml and storing into to a List<Book>
(The code is working fine. I just want to ensure I'm doing the right way, as per industry standards).
books.xml: (only partial xml is presented)
<?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>
Content Handler:
public class MyFirstContentHandler implements ContentHandler { private List<Book> books = new ArrayList<Book>(); private Book book = null; private String elementName = null; @Override public void characters(char[] ch, int start, int length) throws SAXException { // TODO Auto-generated method stub String value = new String(ch, start, length); if(null != elementName) { switch(elementName) { case "author": book.setAuthor(value); elementName = null; break; case "title": book.setTitle(value); elementName = null; break; case "genre": book.setGenre(value); elementName = null; break; case "price": book.setPrice(Double.parseDouble(value)); elementName = null; break; case "publish_date": DateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd"); try { book.setPublishDate(dateFormat.parse(value)); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } elementName = null; break; case "description": book.setDescription(value); elementName = null; break; } } } @Override public void endDocument() throws SAXException { // TODO Auto-generated method stub } @Override public void endElement(String uri, String localName, String qName) throws SAXException { // TODO Auto-generated method stub if(localName.equals("book")) { books.add(book); book = null; } } @Override public void endPrefixMapping(String prefix) throws SAXException { // TODO Auto-generated method stub } @Override public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { // TODO Auto-generated method stub } @Override public void processingInstruction(String target, String data) throws SAXException { // TODO Auto-generated method stub } @Override public void setDocumentLocator(Locator locator) { // TODO Auto-generated method stub } @Override public void skippedEntity(String name) throws SAXException { // TODO Auto-generated method stub } @Override public void startDocument() throws SAXException { // TODO Auto-generated method stub } @Override public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { // TODO Auto-generated method stub // System.out.println(localName); // System.out.println(atts.getValue(atts.getLocalName(0))); elementName = localName; if(localName.equals("book")) book = new Book(atts.getValue(atts.getLocalName(0))); } @Override public void startPrefixMapping(String prefix, String uri) throws SAXException { // TODO Auto-generated method stub } public List<Book> getBooks() { return books; } }
Main Program: (I iterate over the List and print the book details)
public class MyFirstSAXParser { public static void main(String args[]) { try { //Vreate instance (xml reader) needed for parsing XMLReader xmlReader = XMLReaderFactory.createXMLReader(); //Register content handler MyFirstContentHandler contentHandler = new MyFirstContentHandler(); xmlReader.setContentHandler(contentHandler); //Register error handler //Parse InputSource inputSource = new InputSource(new FileReader("books.xml")); xmlReader.parse(inputSource); List<Book> books = contentHandler.getBooks(); for(Book book: books) { System.out.println("Book:"); System.out.println("\tId: "+book.getId()); System.out.println("\tAuthor: "+book.getAuthor()); System.out.println("\tTitle: "+book.getTitle()); System.out.println("\tGenre: "+book.getGenre()); System.out.println("\tPrice: "+book.getPrice()); System.out.println("\tPublish Date: "+book.getPublishDate()); System.out.println("\tDescription: "+book.getDescription()); } } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }