Java – How to parse a namespace using the SAX parser


Using a twitter search URL ie. returns CSS that has an item that looks like:

      <title>@UberTwiter still waiting for @ubertwitter  android app!!!</title>
      <description>still waiting for an app!!!</description>
      <pubDate>Sat, 14 Aug 2010 15:33:44 +0000</pubDate>
      <author>Some Twitter User</author>
      <media:content type="image/jpg" height="48" width="48" url=""/>

Pretty simple. My code parses out everything (title, link, description, pubDate, etc.) without any problems. However, I'm getting null on:


I'm using Java to parse the RSS feed. Do I have to handle compound localnames differently than I would a more simple localname?

This is the bit of code that parses out Link, Description, pubDate, etc:

    public void endElement(String uri, String localName, String name)
            throws SAXException {
        super.endElement(uri, localName, name);
        if (this.currentMessage != null){
            if (localName.equalsIgnoreCase(TITLE)){
            } else if (localName.equalsIgnoreCase(LINK)){
            } else if (localName.equalsIgnoreCase(DESCRIPTION)){
            } else if (localName.equalsIgnoreCase(PUB_DATE)){
            } else if (localName.equalsIgnoreCase(GUID)){
            } else if (uri.equalsIgnoreCase(AVATAR)){
            } else if (localName.equalsIgnoreCase(ITEM)){

startDocument looks like:

    public void startDocument() throws SAXException {
        messages = new ArrayList<Message>();
        builder = new StringBuilder();


startElement looks like:

    public void startElement(String uri, String localName, String name,
            Attributes attributes) throws SAXException {
        super.startElement(uri, localName, name, attributes);
        if (localName.equalsIgnoreCase(ITEM)){
            this.currentMessage = new Message();


Best Solution

An element like <google:image_link> has the local name image_link belonging to the google namespace. You need to ensure that the XML parsing framework is aware of namespaces, and you'd then need to find this element using the appropriate namespace.

For example, a few SAX1 interfaces in package org.xml.sax has been deprecated, replaced by SAX2 counterparts that include namespace support (e.g. SAX1 Parser is deprecated and replaced by SAX2 XMLReader). Consult the documentation on how to specify the namespace uri or qualified (prefixed) qName.

See also