SAXParser的:只处理特定的孩子的家长 [英] SAXParser: handle only specific parent childs

查看:101
本文介绍了SAXParser的:只处理特定的孩子的家长的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有XML结构

 <数据>
   < ID> ID< / ID>
   <标题> dataTitle< /标题>
   <输入>
      <标题>&TITLE1 LT; /标题>
   < /进入>
   <输入>
      <标题>&TITLE2 LT; /标题>
   < /进入>
< /数据>

和我要分析它,并在列表中只保存下的条目标题元素。我如何可以检查的endElement那个标题是在条目?
不是我有NullPointerExpception因为解析器试图保存标题是数据的孩子。

  @覆盖
公共无效的startElement(URI字符串,字符串的localName,字符串QNAME,属性的属性)抛出的SAXException {
    elementOn =真;
    如果(入口.equals(的localName)){
        歌=新曲();
    }
}
@覆盖
公共无效的endElement(URI字符串,字符串的localName,字符串QNAME)抛出的SAXException {
    elementOn = FALSE;    如果(称号.equalsIgnoreCase(的localName)){
        song.setTitle(elementValue);
    }否则如果(入口.equalsIgnoreCase(的localName)){
        songList.add(歌曲);
    }
}


解决方案

在这种情况下,你可以的startElement和endElement使用堆栈的的和的弹出的在CDATA分别事件。把检查的endElement事件,因此只有您需要的数据存储

I have xml structure

<data>
   <id>id</id>
   <title>dataTitle</title>
   <entry>
      <title>title1</title>
   </entry>
   <entry>
      <title>title2</title>
   </entry>
</data>

And I want to parse it and save in list only title elements under entry. How can I check in endElement that title is under entry? Not I have NullPointerExpception because parser tries to save title which is data child.

@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
    elementOn = true;
    if ("entry".equals(localName)) {
        song = new Song();
    }
}


@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
    elementOn = false;

    if ("title".equalsIgnoreCase(localName)) {
        song.setTitle(elementValue);
    } else if ("entry".equalsIgnoreCase(localName)) {
        songList.add(song);
    }
}

解决方案

In this case, you can use a stack to push and pop the cData at startElement and endElement events respectively. Put a check in the endElement event so that only the data you require is stored

这篇关于SAXParser的:只处理特定的孩子的家长的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆