[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();

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

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

        content = new StringBuilder();

    }

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

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

        if(qName.equals(“product”)) {
            products.add(product);
        }else if(qName.equals(“name”)) {
            product.setName(content.toString());
        }else if(qName.equals(“price”)) {
            product.setPrice(Double.parseDouble(content.toString()));
        }
    }
}

Now you can check the parser implementation:

XMLReader reader = XMLReaderFactory.createXMLReader(); 
ParseProduct pp = new ParseProduct(); 
reader.setContentHandler(pp); 
InputStream is = new FileInputStream("src/myFile.xml"); 
InputSource myFile = new InputSource(is); 
reader.parse(myFile); 
System.out.println(pp.getProducts());

 

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s