2010-04-25 84 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