Andy
Andy

Reputation: 45

Issue with SAXparser

I've implemented a SAXparser in my application which has worked fine previously but i'm having problems with a new XML document.

This is my parser

public List<Article> getLatestArticles(String feedUrl) {
URL url = null;
    try {

        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();

        url = new URL(feedUrl);

        xr.setContentHandler(this);
        xr.parse(new InputSource(url.openStream()));


    } catch (IOException e) {
        Log.e("RSS Handler IO", e.getMessage() + " >> " + e.toString());
    } catch (SAXException e) {
        Log.e("RSS Handler SAX", e.toString());
    } catch (ParserConfigurationException e) {
        Log.e("RSS Handler Parser Config", e.toString());
    }
    catch (java.lang.IllegalArgumentException e){
        Log.e("RSS Handler lang", e.getMessage() + " >> " + e.toString());
    }

    return articleList;
}

The parser starts off ok but then i get a java.lang.IllegalArgumentException error. I believe this may be due to an element with no value in my xml feed, it looks like this <Description/>.

Any suggestion on how to fix this would be much appreciated.

Upvotes: 0

Views: 644

Answers (3)

Ajay Kumar Meher
Ajay Kumar Meher

Reputation: 1952

<Description/> is the xml construction issue for SAXParser. have a look into the structure.

Ideally it should be </Description> as a closing tag.

For self-closing tags SAXParser will assume it as a closing tag.

So instead of startElement you will get a call from endElement.

Upvotes: 0

Rickey
Rickey

Reputation: 7880

The connection could close before all the data downloads. Try using a BufferedInputStream and see if that helps:

BufferedInputStream _url_ = new BufferedInputStream(new URL(feedUrl).openStream());

...

BufferedReader isr = new BufferedReader(new InputStreamReader(_url_));
InputSource is = new InputSource(isr);
xr.parse(is);

Upvotes: 0

user1671629
user1671629

Reputation: 51

If </Description> is a self closing tag (i.e. it has not opening <Description> tag and no text value) then this syntax is perfectly correct.

It is hard to tell exactly what is causing the error without seeing the callback methods (e.g. startElement method) but there is one major gottcha that you can check

The SAX parse method throws an illegalArguementException if the InputStream is null. It might be worth checking the value coming into the SAX parser.

You can use the following code to check the input stream for nulls.

InputStreamReader reader = new InputStreamReader(url.openStream());

if (!reader.ready()) {
    System.out.println("error");
}

Upvotes: 1

Related Questions