简体   繁体   中英

Parsing XML file with SAX parser having too many tags

I am Having a xml file with around 60 to 70 tags. while calling the callbacks method of SAX Parsers startElement,endElement,characters the excessive use of if else makes code extremely painful.Are there any other way through which i can make my code more readable?

There are other way, named DOM , StAx etc. Choose your flexible one. But, SAX is more efficient in memory and time. For details, see: http://docs.oracle.com/javase/tutorial/jaxp/index.html

As I understood, you want to execute different methods based on what SAX has just read. I can't think of a way to do this. It seems to me that you are stuck using if-else/switch statements in your Handler methods startElement, endElement, characters etc.

If you find your if-else statements too complex you could extract code from if clauses to separate method for example:

@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
    if (ELEMENT1.equalsIgnoreCase(qName)) {
        createElement1();
    } else if (ELEMENT2.equalsIgnoreCase(qName) {
        createElement2();
    } else {
        createDefaultElement();
    }
}

Check XMLDog

You can write Expressions and then evaluate them inline later avoiding the painful series of if tests . The additional benefit is that it uses a streaming parser (SAX) and avoids the expensive in-memory parsing that XPath requires.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM