[JAVA] – How to use a StAX to parse a XML file ? You can get a list with all data.

What is it ?

The StAX, which has a very similar operation with SAX. It is also based on events, but while the SAX API itself invokes the methods defined in our handler in StAX managed to catch a “list” of all events and scroll through them one by one. The advantage is that, being a “list”, you can return to the previous event, if necessary.

When I should use it ?

As a strategy based on events, the file is not loaded into memory, so it is interesting for situations in which only part of the file is useful.

How to use it ?

Below is an example:

InputStream myFile = new FileInputStream(“src/myFile.xml”);
XMLEventReader events = XMLInputFactory.newInstance()
                                         .createXMLEventReader(myFile);
List<Product> productList = new ArrayList<>();
while(events.hasNext()){
    XMLEvent event = events.nextEvent();
    if(event.isStartElement() && event.asStartElement()
                          .getName().getLocalPart().equals("product")) {
        Product prod = ParseProduct(events);
        productList.add(prod);
    }
}


private static Produto ParseProduct(XMLEventReader events) 
                                                       throws Exception {

Product prod = new Product();

        while(events.hasNext()) {
            XMLEvent event = events.nextEvent();
            if(event.isEndElement() 
                     && event.asEndElement().getName().getLocalPart()
                                                     .equals("produto")) {
                break;
            }

            if(event.isStartElement() 
                     && event.asStartElement().getName()
                                         .getLocalPart().equals("nome")) {
                event = events.nextEvent();
                String name = event.asCharacters().getData();
                prod.setName(name);
            }

            if(event.isStartElement() 
                     && event.asStartElement().getName()
                                       .getLocalPart().equals("price")) {
                event = events.nextEvent();
                Double price = Double.parseDouble(event.asCharacters()
                                                              .getData());
                prod.setPrice(price);
            }

        }

        return prod;
}

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