【问题标题】:SAX Parser returns same element two times with 2nd time as emptySAX Parser 两次返回相同的元素,第二次为空
【发布时间】:2014-10-19 14:43:25
【问题描述】:

当我尝试解析简单的 xml 文件时,我的 Sax 解析器正在做奇怪的事情,

这是我的 xml 文件,

<?xml version="1.0"?>
<organization>
                <employee>
                                <title>Harry0</title>
                                <link>Smith0</link>
                                <date>hs0</date>
                                <salary>200000-0</salary>
                </employee>

                <employee>
                                <title>Harry1</title>
                                <link>Smith1</link>
                                <date>hs1</date>
                                <salary>300000-1</salary>
                </employee>

                 <employee>
                                <title>Harry2</title>
                                <link>Smith2</link>
                                <date>hs2</date>
                                <salary>300000-2</salary>
                </employee>
</organization>

现在如果我只想读取 title 元素,

String elementValue = null;
String localName = null;
@Override
public void startElement(String uri, String localName, String qName,
        Attributes attributes) throws SAXException {
            this.localName = localName;
}


@Override
public void characters(char[] ch, int start, int length)
        throws SAXException {
        elementValue = new String(ch, start, length);
        if (localName.equals("title")){
            Log.e(localName,elementValue);
        }

}

输出是,

10-19 14:41:02.261: E/title(7754): Harry0
10-19 14:41:02.261: E/title(7754):                                 
10-19 14:41:02.281: E/title(7754): Harry1
10-19 14:41:02.297: E/title(7754):                                 
10-19 14:41:02.297: E/title(7754): Harry2
10-19 14:41:02.297: E/title(7754):   

空行和标题行的标签名称相同,即title

为什么 Sax Parser 会返回所有内容两次?

【问题讨论】:

    标签: java android saxparser


    【解决方案1】:

    您不会覆盖 endElement() 方法。 characters() 可能会被多次调用,您应该收集您感兴趣的数据,而不仅仅是在第一次调用 characters() 时分配它。

    然后解析器命中&lt;/title&gt; 标记,但您看不到它并收集另一块字符,直到下一个&lt;link&gt; 标记。您应该覆盖 startElement 和 endElement 方法,收集您的字符串并在点击endElement() 时报告它们

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-06-12
      • 2017-01-10
      • 1970-01-01
      • 1970-01-01
      • 2021-06-03
      • 2020-04-10
      • 1970-01-01
      相关资源
      最近更新 更多