Using a SAX parser to map an XML to a POJO bean

I am using the SAX parser which comes bundled with the jdk. I am using jdk1.5 but without the enhanced loop I have used below it would work as well with jdk1.4
Remember a SAX parser is lighter on memory and is faster, but a bit more complicated to code.

So here goes:

SaxMain.java The main class

package com.mattiz.sax.reader;

import java.io.IOException;
import java.util.ArrayList;

import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;

public class SaxMain {

	public static void main(String args[]) {
		try {
			XMLReader parser = XMLReaderFactory.createXMLReader();
			DefaultHandler saxHandler = new SaxHandler();
			parser.setContentHandler(saxHandler);
			parser.parse("mapper.xml");
			parser = null;
			ArrayList elArray = ((SaxHandler) saxHandler)
					.getElementArray();
			for (ElementsVO a : elArray) {
				System.out.print(" Group is " + a.getGroup());
				System.out.print(" Chemical Name is " + a.getChemicalName());
				System.out
						.print(" Chemical Symbol is " + a.getChemicalSymbol());
				System.out.print(" Latin Name is " + a.getLatinName());
				System.out.println("");
				System.out.println("**********");
			}
		} catch (SAXException e) {
			// TODO
			e.printStackTrace();
		} catch (IOException e) {
			// TODO
			e.printStackTrace();
		}
	}
}

SaxHandler.java Here is where the parsing is done:

package com.mattiz.sax.reader;
 
import java.util.ArrayList;
 
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
 
public class SaxHandler extends DefaultHandler {
 
    private boolean insideChemicalSymbol = false;
 
    private boolean insideChemicalName = false;
 
    private String chemicalSymbol = "";
 
    private String chemicalName = "";
 
    private String group = "";
 
    private String latin = "";
 
    private ArrayList elementArray = new ArrayList();
 
    public void startElement(String uri, String localName, String element_name,
            Attributes attributes) throws SAXException {
        if (localName.equals("ElementSet")) {
            int length = attributes.getLength();
            // Each attribute
            for (int i = 0; i < length; i++) {
                // Get names and values to each attribute
                String name = attributes.getQName(i);
                if (name.equals("group")) {
                    group = attributes.getValue(i);
                }
            }
        }
        if (localName.equals("ChemicalSymbol")) {
            insideChemicalSymbol = true;
            int length = attributes.getLength();
            // Each attribute
            for (int i = 0; i < length; i++) {
                // Get names and values to each attribute
                String name = attributes.getQName(i);
                if (name.equals("latin")) {
                    latin = attributes.getValue(i);
                }
            }
        }
        if (localName.equals("ChemicalName")) {
            insideChemicalName = true;
        }
    }
 
    public void characters(char[] ch, int start, int len) throws SAXException {
 
        if (insideChemicalSymbol) {
            chemicalSymbol = (new String(ch, start, len)).trim();
        }
        if (insideChemicalName) {
            chemicalName = (new String(ch, start, len)).trim();
        }
    }
 
    public void endElement(String uri, String localName, String qName)
            throws SAXException {
        if (localName.equals("ChemicalSymbol")) {
            insideChemicalSymbol = false;
        }
        if (localName.equals("ChemicalName")) {
            insideChemicalName = false;
        }
        if (localName.equals("Element")) {
            ElementsVO elVO = new ElementsVO();
            elVO.setGroup(group);
            elVO.setChemicalName(chemicalName);
            elVO.setChemicalSymbol(chemicalSymbol);
            elVO.setLatinName(latin);
            elementArray.add(elVO);
        }
    }
 
    public ArrayList getElementArray() {
        return elementArray;
    }
}

ElementsVO.java that maps to the xml

package com.mattiz.sax.reader;

public class ElementsVO {

	private String group;
	private String chemicalSymbol;
	private String chemicalName;
	private String latinName;

	public String getLatinName() {
		return latinName;
	}
	public void setLatinName(String latinName) {
		this.latinName = latinName;
	}
	public String getChemicalName() {
		return chemicalName;
	}

	public void setChemicalName(String chemicalName) {
		this.chemicalName = chemicalName;
	}
	public String getChemicalSymbol() {
		return chemicalSymbol;
	}
	public void setChemicalSymbol(String chemicalSymbol) {
		this.chemicalSymbol = chemicalSymbol;
	}

	public String getGroup() {
		return group;
	}
	public void setGroup(String group) {
		this.group = group;
	}
}

mapper.xml
The xml to be mapped to the bean:

<?xml version="1.0" encoding="UTF-8"?>
<Root>
    <ElementSet group="Reactive Elements">
        <Element>
            <ChemicalSymbol latin="Natrium">Na</ChemicalSymbol>
            <ChemicalName>Sodium</ChemicalName>
        </Element>
        <Element>
            <ChemicalSymbol latin="Kalium">K</ChemicalSymbol>
            <ChemicalName>Potassium</ChemicalName>
        </Element>
    </ElementSet>
    <ElementSet group="Metals">
        <Element>
            <ChemicalSymbol latin="Stibium">Sb</ChemicalSymbol>
            <ChemicalName>Antimony</ChemicalName>
        </Element>
        <Element>
            <ChemicalSymbol latin="Cuprum">Cu</ChemicalSymbol>
            <ChemicalName>Copper</ChemicalName>
        </Element>
        <Element>
            <ChemicalSymbol latin="Stannum">Sn</ChemicalSymbol>
            <ChemicalName>Tin</ChemicalName>
        </Element>
    </ElementSet>
</Root>

About cuppajavamattiz
Matty Jacob - Avid technical blogger with interests in J2EE, Web Application Servers, Web frameworks, Open source libraries, Relational Databases, Web Services, Source control repositories, ETL, IDE Tools and related technologies.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: