2010-04-25 97 views
2

我在使用SAX解析自我關閉XML標記時遇到問題。我試圖從Google Base API中提取鏈接標記。我在解析常規標記方面取得了合理的成功。使用SAX解析器解析自我關閉XML標記時遇到問題

這裏是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&amp;icep_vectorid=263602&amp;kwid=1&amp;mtid=691&amp;crlp=1_263602&amp;icep_item_id=170468125748&amp;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++; 
    } 
} 
+0

你應該確保所有的塊代碼都縮進四個空格(我這次爲你編輯過)。這也適用於xml示例。 – 2010-04-25 07:48:32

+0

有什麼症狀?這兩種方法都不會被調用,或者只有一種? – 2010-04-25 07:53:08

+0

會記住這一點! 只調用啓動元素。 – sandesh 2010-04-25 08:01:51

回答

1

characters做什麼是傳遞XML元素標記之間的內容(以塊的形式,每個方法調用一個塊)。所以 如果你有一個像

<Foo someattrib=「」 /> 

那麼characters XML元素不會被調用,因爲有解析器給大家介紹一下沒有內容在那裏。

如果你是依靠其到達這裏稱爲即使標籤是空的,你做錯了你的角色的方法。

字符方法添加元素文本到緩衝區,但的startElement和endElement需要在負責清理,並從緩衝區中讀取的,因爲的endElement是你知道你已經收到的所有元素文本的地方。如果沒有東西可讀,應該可以讓字符不被調用。

因爲您可能尚未擁有任何一個字符中的所有內容,請致電此方法中不得有任何業務邏輯。如果有,那麼你的代碼在某些時候不起作用。

有關如何實現字符,請參見this example。如果你想要做的是讀取屬性值,請參閱this example

+0

的是你能夠找出如何解析呢?我有解析相同類型的XML文檔同樣的困難。 – Rudy 2018-01-04 20:55:16

+0

@Rudy:增加了更多的解釋,並鏈接到我寫其他答案的例子。 – 2018-01-05 02:21:59