展会信息港展会大全

Android 解析gbk、gb2312编码的xml文件
来源:互联网   发布日期:2016-01-13 21:58:47   浏览:1975次  

导读:Android 支持三种解析xml文件的方式,dom,sax,pull,我用的比较多的是sax解析,但发现sax默认只解析utf-8编码的xml文件;通过网上搜索,最终找到了解决办法:1.就是先判断URL资源上的xml文件的编码方式2.然后......

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();

通过以上三步就可以解析gbk或者gb2312编码的xml文件,将网络上的rss资源文件解析后,用ListView显示出来,就成了一个简单的rss

赞助本站

人工智能实验室

相关热词: 解析 gbk gb2312 xml 编码

AiLab云推荐
展开

热门栏目HotCates

Copyright © 2010-2024 AiLab Team. 人工智能实验室 版权所有    关于我们 | 联系我们 | 广告服务 | 公司动态 | 免责声明 | 隐私条款 | 工作机会 | 展会港