Sax 解析xml 编码 格式为gb2312

转自:http://lovezhou.iteye.com/blog/839990

Android 支持三种解析xml文件的方式,dom,sax,pull,我用的比较多的是sax解析,但发现sax默认只解析utf-8编码的xml文件;
通过网上搜索,最终找到了解决办法:
1.就是先判断URL资源上的xml文件的编码方式
2.然后通过InputStreamReader 设定好编码,然后将InputStreamReader通过InputSource的构造方法传给InputSource
3.sax解析InputSource资源时,就会按照指定的编码方式解析

1.判断url资源上的xml文件编码方式,需要通过第三方的jar文件
//得到探测器代理对象
CodepageDetectorProxy detector = CodepageDetectorProxy.getInstance();
//向代理对象添加探测器
detector.add(JChardetFacade.getInstance());
//得到编码字符集对象
Charset charset = detector.detectCodepage(url);
//得到编码名称
String encodingName = charset.name();

2.通过InputStreamReader对象设定解析时的编码
InputSource inputSource=null;
InputStream stream = null;

//如果是GBK编码
if("GBK".equals(EncodingUtil.checkEncoding(url))){
stream = url.openStream();
//通过InputStreamReader设定编码方式
InputStreamReader streamReader = new InputStreamReader(stream,"GBK");
inputSource = new InputSource(streamReader);
}else{
//是utf-8编码
inputSource = new InputSource(url.openStream());
inputSource.setEncoding("UTF-8");
}

3.使用sax解析InputSource对象
ChinaNews chinaNews = SAXRssService.readRssXml(inputSource);
newsItems=chinaNews.getNewsItems();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值