我正在学习Java SAX API。我使用php编写了自己的XML feed。这是XML文档
现在,当我想将应用程序输出到控制台时,什么也没发生。我将问题定位到扩展endElement
的XMLHandler
中的DefaultHandler
方法。这是我的实现。
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++;
}
事实证明,
localName
一直为空,因此条件永远不成立,代码也从未进入决策块。另一方面,qName
正确显示了所有名称,并且一旦我将变量更改为qName
,List<Item> items
集合类型便会填满并正常工作。我在这里问为什么qName起作用而不是localName?而IBM DeveloperWorks的教程使用了RSS提要,而
localName
对他来说非常适合。附言这是IBM教程使用的提要:http://www.androidster.com/android_news.rss
最佳答案
根据SAX namespace for Java API,
默认情况下,XML阅读器将报告命名空间URI和localName
对于属于命名空间的每个元素,在开始和结尾处
结束处理程序。
也许,如果您向XML添加名称空间并在该名称空间中定义元素,则它将返回有效的localName
。本文还提到,通过名称空间处理,某些实现将返回空的qName
。