解析XML各種異常

The markup in the document following the root element must be well-formed.

XML是樹狀結構,一定要有個最外層的標籤套住

 

 Invalid byte 1 of 1-byte UTF-8 sequence 異常分析和解決

“org.dom4j.DocumentException: Invalid byte 1 of 1-byte UTF-8 sequence.”異常分析和解決:

分析:
該異常由下面的reader.read(file);語句拋出:
SAXReader reader = new SAXReader();
Document doc = reader.read(file);

產生這個異常的原因是:
所讀的xml文件實際是GBK或者其他編碼的,而xml內容中卻用<?xml version="1.0" encoding="utf-8"?>指定編碼爲utf-8,所以就報異常了!

解決方法:

在解析XML前,將XML編碼爲UTF-8。

如:req.setCharacterEncoding("UTF-8");

如:new ByteArrayInputStream(submitDataParam.getBytes("UTF-8"))

 

Invalid byte 2 of 2-byte UTF-8 sequence 異常分析和解決

原因:
saxReader.read()讀取的流中包含中文報錯:
解決:
SAXReader saxReader = new SAXReader(); 
byte[] bytes = requestMsg.getBytes(); 
InputStream in = new ByteArrayInputStream(bytes); 
InputStreamReader strInStream = new InputStreamReader(in, "GBK"); //即在讀流時指定編碼
Document document = saxReader.read(strInStream);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章