SAX解析和特殊字符 [英] SAX parsing and special characters

查看:135
本文介绍了SAX解析和特殊字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用SAX解析器从xml文件解析一些数据。我的xml如下:

I want to parse some data from an xml file using SAX parser. My xml is as follows:

<categories>
 <cat>Pies &amp; past</cat>
 <cat>Fruits</cat>
</categories>

为了解析这些数据,我扩展了DefaultHandler。

In order to parse this data I extend DefaultHandler.

解析后的输出为:

cat 1 = Pies

cat 2 = &

cat 3 = past

cat 4 = Fruits

为什么会发生这种情况而不是:

Why is this happening instead of getting:

cat 1 = Pies & past

cat 2 = Fruits


推荐答案

我的猜测是,您将每次调用字符视为提供 cat 元素的完整文本。您应该对处理程序进行编码,以便连续调用字符累积文本,并且只在 endElement 事件中捕获它:

My guess is that you are treating each call to characters as delivering the complete text for a cat element. You should code your handler so that successive calls to characters accumulate the text, and you only capture it on the endElement event:

public class CatHandler extends DefaultHandler {
    private StringBuilder chars = new StringBuilder();

    public void startElement(String uri, String lName, String qName, Attributes a)
    {
        final String name = qName == null ? lName : qName;
        if ("cat".equals(name)) {
            chars.setLength(0);
        } else . . .
    }

    public void endElement(String uri, String lName, String qName) {
        final String name = qName == null ? lName : qName;
        if ("cat".equals(name)) {
            String catName = chars.toString();
            // do something with cat name
        } else . . .
    }

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

这篇关于SAX解析和特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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