2012-04-09 98 views
0

在我的应用程序中,我有一些要解析的50到100个数据...还有一些2 MB大小以内的图像...所有这些都将被检索到单个活动并进行排序和显示那里...Android SAX解析检索速度很慢

但它需要约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; 
     } 
} 
+0

是'XmlHandler'类,你能告诉我们它的代码? – 2012-04-09 12:16:33

+0

@DonRoby检查代码 – subrussn90 2012-04-09 12:22:50

回答

2

答案很可能是您正在使用的SAX解析器正在检查Internet的XML模式或DTD的内容。如果你写一个绕过这些检查的entityResolver,你可能会改善你的开始时间(通常是2分钟左右)。

请参阅这里了解更多详情。

How to read well formed XML in Java, but skip the schema?

这解决了使用的Xerces对我来说这个问题......

3

你真的应该分析代码,并找出它的花时间。

我可以在您的发布代码中看到一个性能问题和一个正确性问题。

通过在您的endElement代码中添加一些else用法,您将获得一些好处。一旦你知道localName匹配的东西没有必要检查它对所有后来的可能性不可能匹配。

这可能没有太大的收获,但它的确值得尝试。

您的characters方法是错误的,但这与正确性而不是效率有关。请参阅my answer了解有关SAX解析的其他问题以及如何编写正确的characters方法。此更改还需要更改endElement如何获取该值,因为它必须收集到缓冲区中。