[英]Trouble parsing self closing XML tags using SAX parser
我在使用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是您知道已收到所有元素文本的地方。 如果沒有什么可讀的,那么就不應該調用字符。
因為您可能在任何一個字符調用中都沒有所有內容, 所以該方法中不得有任何業務邏輯。 如果有,那么你的代碼在某些時候將無法運行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.