Java SAX解析器startElement没有看到标签

时间:2012-06-07 20:32:34

标签: java android xml-parsing sax saxparser

示例XML:

<rss version="2.0">
<channel>
<title>The Channel Title Goes Here</title>
<description>
The explanation of how the items are related goes here
</description>
<link>/events</link>
<item>
<title>
<![CDATA[ some title ]]>
</title>
<description>
<![CDATA[ ]]>
</description>
<content:encoded xmlns:content="http://stuff.com">
<![CDATA[ 
    <event>
        <name>some name</name>
        <startdate>some date</startdate>
        <starttime>some time</starttime>
        <location>some place</location>
        <description></description>
    </event>
]]>
</content:encoded>
</item>
<item>
</item>
...
</channel>
</rss>

我的SAX解析器startElement方法永远不会进入以下if语句,但sysout会将“event”打印到logcat。为什么它永远不会发现localName.equals("event")true

@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException 
{
    System.out.println(localName);

    if (localName.equals("event"))      // <-- never goes in here
    {
        // do stuff
    }
}

是否与CDATA有关,以及我如何设置解析器?以下是我实例化所有内容的方法:

URL sourceUrl = new URL(kEventsURL);

SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();

MyXMLHandler myXMLHandler = new MyXMLHandler();
xr.setContentHandler(myXMLHandler);
xr.parse(new InputSource(sourceUrl.openStream()));

2 个答案:

答案 0 :(得分:1)

阅读第一个回答here,了解为什么它无法识别标签启动。您应该运行另一个包含来自element的文本的解析器。

答案 1 :(得分:0)

尝试“qName”

而不是“localName”