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