[英]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.