SAX解析问题

时间:2012-03-16 05:58:08

标签: android xml parsing sax

如何解析像这样的XML

<rss version="0.92">
<channel>
<title>MyTitle</title>
<link>http://myurl.com</link>
<description>MyDescription</description>
<lastBuildDate>SomeDate</lastBuildDate>
<docs>http://someurl.com</docs>
<language>SomeLanguage</language>

<item>
    <title>TitleOne</title>
    <description><![CDATA[Some text.]]></description>
    <link>http://linktoarticle.com</link>
</item>

<item>
    <title>TitleTwo</title>
    <description><![CDATA[Some other text.]]></description>
    <link>http://linktoanotherarticle.com</link>
</item>

</channel>
</rss>

请任何帮助。

1 个答案:

答案 0 :(得分:1)

试试这个

public class ExampleHandler extends DefaultHandler {

private Channel channel;
private Items items;
private Item item;
private boolean inItem = false;

private StringBuilder content;

public ExampleHandler() {
    items = new Items();
    content = new StringBuilder();
}

public void startElement(String uri, String localName, String qName, 
        Attributes atts) throws SAXException {
    content = new StringBuilder();
    if(localName.equalsIgnoreCase("channel")) {
        channel = new Channel();
    } else if(localName.equalsIgnoreCase("item")) {
        inItem = true;
        item = new Item();
    }
}

public void endElement(String uri, String localName, String qName) 
        throws SAXException {
    if(localName.equalsIgnoreCase("title")) {
        if(inItem) {
            item.setTitle(content.toString());
        } else {
            channel.setTitle(content.toString());
        }
    } else if(localName.equalsIgnoreCase("link")) {
        if(inItem) {
            item.setLink(content.toString());
        } else {
            channel.setLink(content.toString());
        }
    } else if(localName.equalsIgnoreCase("description")) {
        if(inItem) {
            item.setDescription(content.toString());
        } else {
            channel.setDescription(content.toString());
        }
    } else if(localName.equalsIgnoreCase("lastBuildDate")) {
        channel.setLastBuildDate(content.toString());
    } else if(localName.equalsIgnoreCase("docs")) {
        channel.setDocs(content.toString());
    } else if(localName.equalsIgnoreCase("language")) {
        channel.setLanguage(content.toString());
    } else if(localName.equalsIgnoreCase("item")) {
        inItem = false;
        items.add(item);
    } else if(localName.equalsIgnoreCase("channel")) {
        channel.setItems(items);
    }
}

public void characters(char[] ch, int start, int length) 
        throws SAXException {
    content.append(ch, start, length);
}

public void endDocument() throws SAXException {
    // you can do something here for example send
    // the Channel object somewhere or whatever.
}

}

其中Item,Items和Channel是getter setter class ...

了解更多信息,请访问此问题How to parse XML using the SAX parser