Search code examples
javaandroidxml-parsingsaxsaxparser

Java SAX parser startElement not seeing tags


Sample XML:

<rss version="2.0">
<channel>
<title>The Channel Title Goes Here</title>
<description>
The explanation of how the items are related goes here
</description>
<link>/events</link>
<item>
<title>
<![CDATA[ some title ]]>
</title>
<description>
<![CDATA[ ]]>
</description>
<content:encoded xmlns:content="http://stuff.com">
<![CDATA[ 
    <event>
        <name>some name</name>
        <startdate>some date</startdate>
        <starttime>some time</starttime>
        <location>some place</location>
        <description></description>
    </event>
]]>
</content:encoded>
</item>
<item>
</item>
...
</channel>
</rss>

My SAX parser startElement method never goes into the following if statement, but the sysout prints "event" to the logcat. Why does it never find localName.equals("event") to be true?

@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException 
{
    System.out.println(localName);

    if (localName.equals("event"))      // <-- never goes in here
    {
        // do stuff
    }
}

Is it something to do with the CDATA and how I set up my parser? Here's how I instantiate everything:

URL sourceUrl = new URL(kEventsURL);

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

MyXMLHandler myXMLHandler = new MyXMLHandler();
xr.setContentHandler(myXMLHandler);
xr.parse(new InputSource(sourceUrl.openStream()));

Solution

  • Read first answer here to understand why it doesn't recognize tag start. You should probably run another parser with text from element.