[JAVA] – How to use SAX to parse a XML file?

First you need implement the class where you will specify the attributes of your file. Look the code below.

public class ParseProduct extends DefaultHandler {

    private List<Product> products = new ArrayList< Product >();
    private Product  product;
    private StringBuilder content = new StringBuilder();

    public void startElement(String uri, String localName,
           String qName, Attributes attributes) throws SAXException {

        if(qName.equals(“product”)) {
            product = new  Product ();

        content = new StringBuilder();


    public void characters(char[] ch, int start, int length) 
                                                  throws SAXException {
        // TODO Auto-generated method stub
        content.append(new String(ch,start,length));

    public void endElement(String uri, String localName, 
                                    String qName) throws SAXException {

        if(qName.equals(“product”)) {
        }else if(qName.equals(“name”)) {
        }else if(qName.equals(“price”)) {

Now you can check the parser implementation:

XMLReader reader = XMLReaderFactory.createXMLReader(); 
ParseProduct pp = new ParseProduct(); 
InputStream is = new FileInputStream("src/myFile.xml"); 
InputSource myFile = new InputSource(is); 


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 )

Facebook photo

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

Connecting to %s