[英]Android SAX parsing retrieval very slow
在我的应用程序中,我有大约 50 到 100 个数据要解析......还有一些 2 MB 大小的图像......所有这些都将被检索到一个活动并在那里排序和显示......
但它需要大约 2 分钟……太多了。
如何减少解析时间?
或者我错误地使用 SAX 解析???请提出建议....
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
/** Send URL to parse XML Tags */
URL sourceUrl = new URL(url);
/** Create handler to handle XML Tags ( extends DefaultHandler ) */
XmlHandler xmlHandler4Profile = new XmlHandler();
xr.setContentHandler(xmlHandler4Profile);
xr.parse(new InputSource(sourceUrl.openStream()));
}
XmlHandler.java 的代码
public class XmlHandler extends DefaultHandler{
static GetXml getxml;
Boolean currentElement = false;
String currentValue = null;
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// TODO Auto-generated method stub
currentElement=true;
if (localName.equals("root"))
{
/** Start */
getxml = new GetXml();
}
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
// TODO Auto-generated method stub
currentElement=false;
//**************************display page************************
if (localName.equalsIgnoreCase("DisplayId"))
getxml.setDisplayId(currentValue);
if (localName.equalsIgnoreCase("DisplayPage"))
getxml.setDisplayPage(currentValue);
//**************************category details************************
if (localName.equalsIgnoreCase("CategoryId"))
getxml.setCategoryId(currentValue);
if (localName.equalsIgnoreCase("CategoryName"))
getxml.setCategory(currentValue);
//**************************news details************************
if (localName.equalsIgnoreCase("Picture"))
getxml.setPictureName(currentValue);
if (localName.equalsIgnoreCase("newsHeading"))
getxml.setNewsHeading(currentValue);
if (localName.equalsIgnoreCase("Mainnews"))
getxml.setMainNews(currentValue);
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
// TODO Auto-generated method stub
if (currentElement) {
currentValue = new String(ch, start, length);
currentElement = false;
}
}
您真的应该剖析您的代码并找出它花费时间的地方。
我可以在您发布的代码中看到一个性能问题和一个正确性问题。
通过在endElement
代码中添加一些else
用法,您会有所收获。 一旦您知道localName
与某些东西匹配,就没有必要根据所有以后不可能匹配的可能性来检查它。
这可能不会有太大收获,但绝对值得一试。
您的characters
方法是错误的,但这与正确性而不是效率有关。 请参阅我对关于 SAX 解析的另一个问题的回答,以了解问题所在以及如何编写正确的characters
方法。 更改还需要更改endElement
获取值的方式,因为它必须收集到缓冲区中。
答案很可能是您正在使用的 SAX 解析器正在检查 inte.net 以获取您的 xml 内容的模式或 DTD。 如果您编写绕过这些检查的 entityResolver,您可能会缩短开始时间(通常为 2 分钟左右)。
有关更多详细信息,请参阅此内容。
这解决了我使用 Xerces 的问题......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.