prometheuspk prometheuspk - 5 months ago 11
Java Question

Why did qName work and LocalName did not?

I was learning the Java SAX API. I made my own XML feed using php. Here is the XML Document

enter image description here

Now when i wanted to make my application output to the console nothing came up. I pinpointed the problem to the

endElement
method in my
XMLHandler
that extends
DefaultHandler
. Here is my implementation of it.

public void endElement(String uri, String localName, String qName) throws SAXException {
//I added the next three lines for debugging
System.out.println("Found End Element " + count + " times");
System.out.println("Localname = " + localName);
System.out.println("QName = " + qName);
super.endElement(uri, localName, qName);
if (this.currentItem != null){
if (localName.equalsIgnoreCase(me.osama.XMLParsing.BaseFeedParser.ITEMNAME)){
currentItem.setItemName(builder.toString());
} else if (localName.equalsIgnoreCase(me.osama.XMLParsing.BaseFeedParser.ITEMSITE)){
currentItem.setItemSite(builder.toString());
} else if (localName.equalsIgnoreCase(me.osama.XMLParsing.BaseFeedParser.ITEMNO)){
currentItem.setItemNo(builder.toString());
} else if (localName.equalsIgnoreCase(me.osama.XMLParsing.BaseFeedParser.ITEM)){
System.out.println(currentItem);
items.add(currentItem);
}
builder.setLength(0);
}
count++;
}


Turns out that
localName
kept on coming empty hence the conditions never held true and the code never went into the decision block. On the other hand
qName
brought all names out properly and once i changed the variable to
qName
the
List<Item> items
collection type did fill up and worked correctly.

I am here to ask why did qName work and not localName? Whereas the tutorial from IBM's DeveloperWorks used an RSS feed and
localName
worked perfectly for him.

P.S. this is the feed the IBM Tutorial used: http://www.androidster.com/android_news.rss

Answer

As per the SAX namespace for Java API,

By default, an XML reader will report a Namespace URI and a localName for every element that belongs in a namespace, in both the start and end handler.

Perhaps, if you add a namespace to the XML and define your elements in that namespace, it would return a valid localName. The article also mentions that with namespace processing, some implementations will return empty qName.

Comments