在android sax解析器

时间:2015-05-08 18:39:22

标签: android parsing sax

我尝试使用android rss news解析此sax parser

final RSSItem currentMessage = new RSSItem();
    RootElement root = new RootElement("rss");
    final List<RSSItem> messages = new ArrayList<RSSItem>();
    Element channel = root.getChild("channel");
    Element item = channel.getChild(ITEM);

但我抓住了例外:

05-08 18:29:25.004    2820-2820/com.xmlsimplesaxparser V/SimpleRss2ParserDemo﹕ android.sax.BadXmlException: Line 1: Root element name does not match. Expected: 'rss', Got: 'http://backend.userland.com/rss2:rss'

当我添加命名空间时:

static final String NAMESPACE ="http://backend.userland.com/rss2";

 final RSSItem currentMessage = new RSSItem();
    RootElement root = new RootElement(NAMESPACE, "rss");
    final List<RSSItem> messages = new ArrayList<RSSItem>();
    Element channel = root.getChild(NAMESPACE, "channel");
    Element item = channel.getChild(NAMESPACE, ITEM);

我得到了NullPointerExeption。如何在sax解析器中使用命名空间?

1 个答案:

答案 0 :(得分:0)

我更正了这个问题:需要为所有标签添加命名空间

final RSSItem currentMessage = new RSSItem();
    RootElement root = new RootElement(NAMESPACE, "rss");
    final List<RSSItem> messages = new ArrayList<RSSItem>();
    Element channel = root.getChild(NAMESPACE, "channel");

    //Element mainTitle = channel.getChild(NAMESPACE,"title");

    Element item = channel.getChild(NAMESPACE,ITEM);

    item.setEndElementListener(new EndElementListener() {
        public void end() {
            messages.add(currentMessage.copy());
        }
    });
    item.getChild(NAMESPACE,TITLE).setEndTextElementListener(new EndTextElementListener() { //this add namespace too
        public void end(String body) {
            currentMessage.setTitle(body);
        }
    });