Can I quickly get the value of a specified tag using the SAX parser?

I want to create a progress bar when importing articles from an XML feed.

Parsing works fine, but for my progress bar, I need to quickly find out the total number <item>

in the feed so that I can determine the percentage that has been uploaded.

My thought was that it would be much faster to do this in PHP and add the "score" to the channel itself - something like this:

<?xml version="1.0" encoding="utf-8"?>
<channel>
<title>My Apps Feed</title>
<link>http://link_to_this_fiel</link>
<language>en-us</language>
<count>42</count>

      

But then I need to be able to quickly access that "count".

At the moment I have RSSHandler.java

one called the following:

//Add all items from the parsed XML
for(NewsItem item : parser.getParsedItems())
{
    //...

      

Note. The minimum API level is 8 for my application.

+3


source to share


2 answers


You can use Xpath to get a specific node value in XML. The sample will look like this:

SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(.....); // get document for your xml here
Element elem = (Element) XPath.selectSingleNode(doc, "channel/count");
System.out.println(elem.getValue());

      



This way you can get the count value directly. But I'm not sure if this is an efficient and quick way to do it. You can use this as an option. Also spend some time reading: SAX analysis is an efficient way to get text nodes

0


source


SAX reads tags in the order in which they appear. Make sure to put your tag at the beginning of the XML, otherwise you will have to parse it anyway. For ease of parsing, I've put it in a self-closing tag attribute with a unique name. Then you wait for the SAX parser to call your method startElement

, check if the tag name matches your tag name count, retrieves the attribute and displays it to the user.

If you want to stop the parser after displaying the score, you can reset it SAXException

.



I assume you already know how to parse the main thread, since you are specifying a progress bar and implying that the parsing may take a while (and doing long tasks on the main thread gives you ANR). In case someone stumbles upon this question that doesn't know: you can use AsyncTask

both publishProgress

(called on the "worker" thread by your code) and onProgressUpdate

(called by Android on the UI thread as soon as you call publishProgress

) to take care of this.

0


source







All Articles