我在使用SAX解析自关闭XML标记时遇到问题。我正在尝试从Google Base API中提取链接标记。我在解析常规标记方面取得了相当的成功。
这是xml的片段
<entry>
<id>http://www.google.com/base/feeds/snippets/15802191394735287303</id>
<published>2010-04-05T11:00:00.000Z</published>
<updated>2010-04-24T19:00:07.000Z</updated>
<category scheme='http://base.google.com/categories/itemtypes' term='Products'/>
<title type='text'>En-el1 Li-ion Battery+charger For Nikon Digital Camera</title>
<link rel='alternate' type='text/html' href='http://rover.ebay.com/rover/1/711-67261-24966-0/2?ipn=psmain&icep_vectorid=263602&kwid=1&mtid=691&crlp=1_263602&icep_item_id=170468125748&itemid=170468125748'/>
.
.
等等
我可以解析更新和发布的标签,但不能解析链接和类别标签。
这是我的startElement和endElement覆盖
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
if (qName.equals("title") && xmlTags.peek().equals("entry")) {
insideEntryTitle = true;
}
xmlTags.push(qName);
}
public void endElement(String uri, String localName, String qName)
throws SAXException {
// If a "title" element is closed, we start a new line, to prepare
// printing the new title.
xmlTags.pop();
if (insideEntryTitle) {
insideEntryTitle = false;
System.out.println();
}
}
xmltags的声明..
private Stack<String> xmlTags = new Stack<String>();
有帮助吗?
这是我在这里的第一篇文章..我希望我遵循发布规则!谢谢你们...
更正:endElement
被召唤。 characters
没有。
public void characters(char[] ch, int start, int length) throws SAXException
{
if (insideEntryTitle)
{
String url= new String(ch, start, length);
System.out.println("url="+title);
i++;
}
}
characters
所做的是在XML元素标记之间传递内容(以块为单位,每个方法调用一个块)。所以,如果你有像这样的XML元素
<Foo someattrib=“” />
然后characters
没有被调用,因为解析器没有内容可以告诉你。
如果你依赖你的字符方法必须在这里被调用,即使标签是空的,你做错了。
characters方法将元素文本添加到缓冲区,但是startElement和endElement需要负责清除和读取缓冲区,因为endElement是您知道已收到所有元素文本的地方。如果没有什么可读的,那么就不应该调用字符。
因为您可能在任何一个字符调用中都没有所有内容,所以该方法中不得有任何业务逻辑。如果有,那么你的代码在某些时候将无法运行。
有关如何实现字符的信息,请参阅this example。如果你想要做的是读取属性值,请参阅this example。