简体   繁体   中英

XPath XML data parsing in android very slow

The xpath.evaluate parsing in android takes about 8-9 seconds for each. I use about 8 different xpath evaluate methods and my program takes about 1 min 35 seconds to load.

I'm using an AsyncTask for this purpose and I don't want to implement other parsers which are not included in the standard JDK.

One of the many laggy xpath evaluate code blocks :

for (int i=1;i<=36;i++){
                      InputSource source16 = new InputSource(new StringReader(hourly));

                      try{
                       humidity = xpath.evaluate("/response/hourly_forecast/forecast["+i+"]/humidity", source16);


                      }
                      catch (Exception e) {
                      e.printStackTrace();
                                  }
                      }

try to get this line to top of your for loop, i'm pretty sure it will solve your problem. But if it doesn't try to not to use it. I mean try to read your string into an inputstream and work with it.

InputSource source16 = new InputSource(new StringReader(hourly));
for (int i=1;i<=36;i++){
                  try{
                   humidity = xpath.evaluate("/response/hourly_forecast/forecast["+i+"]/humidity", source16);


                  }
                  catch (Exception e) {
                  e.printStackTrace();
                              }
                  }

As we know string proccess can be a torture if you don't be more careful.

I had the same trouble when I was doing a swing program with Java SE. I had to call xpath.evalute method about 12 different times, each time taking atleast 2-3 seconds which made my program awfully slow.

The simple solution was to use a substring. It might sound naive and a lot of work, but it actually works if you just have under 10 different parameters to parse from the XML and most importantly the XML is reliable and well formatted.

In your case with just 8 different parameters to parse in the entire document, this method is quite easily achievable. Just use a for-loop too.

Implement something like this : First, parse your entire XML document to a string. Let's call it yourXmlDoc. And store the values of humidity in a String array.

num1=0;
num2=0;
num3=0;
for (int i=0;i<*number of times you need to repeat*;i++){
num1=yourXmlDoc.indexOf("humidity",num3);
num2=yourXmlDoc.indexOf("/humidity",num1);
num3=num2;
humidity[i]=yourXmlDoc.substring(num1+9,num2-1);
System.out.println(humidity[i]);

.. continue with more parameters to parse and let its starting point be num3
}

PS This is possible only in case of a well formatted XML. Otherwise its very hard to implement and is a waste of time.

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