手机版
你好,游客 登录 注册
背景:
阅读新闻

Java 使用dom读取XML文件及对中文字符的支持

[日期:2012-08-29] 来源:Linux社区  作者:soszou [字体:大 中 小]

我本机的开发环境编码是UTF-8;

以下这个方法正常读取不含中文的XML文件是没问题的

 public static Element returnRootElement(String fileName) {
  String deviceInformation = "";
  Document document = null;
  Element root = null;
  try {
   deviceInformation = FileResource.readFile(fileName,UiUtilPlugin.PLUGIN_ID);
   DocumentBuilder builder;
   builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
   InputStream is = new ByteArrayInputStream(
     deviceInformation.getBytes());
   document = builder.parse(is);
   root = document.getDocumentElement();
   return root;
  } catch (Exception e) {
   e.printStackTrace();
  }
  return null;
 }

但是遇到含有中文的字符呢  就会出现这个错误

org.apache.xerces.internal.impl.io.MalformedByteSequenceException: Invalid byte 1 of 1-byte UTF-8 sequence

这是因为SAX’s parser没有设置正确的编码格式,导致读取文件出错。

那原因知道了

我下面贴一下我修改的代码:

很简单,加入这几句就可以了

   InputStream iStream= new ByteArrayInputStream(xmlInformation.getBytes());
   Reader reader = new InputStreamReader(iStream,"GB2312");
   InputSource iSource = new InputSource(reader);
   iSource.setEncoding("GB2312");
   document = builder.parse(iSource);

共同学习。

linux
相关资讯       Java教程 
本文评论   查看全部评论 (1)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款
第 1 楼
* 匿名 发表于 2013/7/10 10:01:21
public static void main(String[] args) {
int num1=2,num2=3;
String name="Sub";
try {
//得到DOM解析器的实例
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
//从DOM获得DOM解析器
DocumentBuilder builder = dbf.newDocumentBuilder();
Document doc;
//把要解析的XML文档转化为输入流,以便DOM解析器解析它
InputStream stream = new FileInputStream("..\\JavaDemo\\src\\com\\game\\xmlname\\MyXml.xml");
doc = buil