简体   繁体   English

使用标签过多的SAX解析器解析XML文件

[英]Parsing XML file with SAX parser having too many tags

I am Having a xml file with around 60 to 70 tags. 我有一个带有大约60到70个标签的xml文件。 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? 在调用SAX Parsers startElement,endElement,的回调方法时,如果过多使用字符,将使代码非常痛苦。是否还有其他方法可以使代码更具可读性?

There are other way, named DOM , StAx etc. Choose your flexible one. 还有其他方法,称为DOMStAx等。选择一种灵活的方法。 But, SAX is more efficient in memory and time. 但是,SAX在内存和时间上效率更高。 For details, see: http://docs.oracle.com/javase/tutorial/jaxp/index.html 有关详细信息,请参见: 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. 据我了解,您想根据SAX刚读的内容执行不同的方法。 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. 在我看来,您在Handler方法的startElement,endElement,characters等中使用if-else/switch语句感到困惑。

If you find your if-else statements too complex you could extract code from if clauses to separate method for example: 如果您发现if-else语句过于复杂,则可以从if子句中提取代码以分离方法,例如:

@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 检查XMLDog

You can write Expressions and then evaluate them inline later avoiding the painful series of if tests . 您可以编写Expressions ,然后内联评估它们,避免痛苦的if tests系列。 The additional benefit is that it uses a streaming parser (SAX) and avoids the expensive in-memory parsing that XPath requires. 另一个好处是它使用了流解析器(SAX),并且避免了XPath所需的昂贵的内存中解析。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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