dom4j解析xml异常记录
最近在使用dom4j直接解析从远程发送过来的xml文件时,在使用dom4j读取输入流时出现了一些字符编码的错误。
源码如下:public void checkXML1(InputStream input){
SAXReader reader = new SAXReader();//input为从远程发送过来的输入流
Document doc = null;
try {
doc = reader.read(input);//这个出现字符编码错误
StringWriter buffer = new StringWriter();
OutputFormat format = new OutputFormat();
format.setEncoding("UTF-8");
format.setIndentSize(4);
format.setNewlines(true);
format.setTrimText(true);
format.setExpandEmptyElements(true);
HTMLWriter writer = new HTMLWriter(buffer,format);
writer.write(doc);
String xml = buffer.toString();
System.out.println("xml:"+xml);
} catch (DocumentException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
错误具体信息如下:org.dom4j.DocumentException: Invalid byte 1 of 1-byte UTF-8 sequence. Nested exception: Invalid byte 1 of 1-byte UTF-8 sequence.有时会出现说文档中有(Unicode oxb2)编码错误。
解决办法:使用InputStreamReader包装此input输入流,源码如下:InputStreamReader inputReader = new InputStreamReader(input,"gbk");//对输入流进行转换成相应的编码就可以了。修改后的源码如下:public void checkXML1(InputStream input){
SAXReader reader = new SAXReader();
Document doc = null;
try {
InputStreamReader inputReader = new InputStreamReader(input,"gbk"); //编码转换
doc = reader.read(inputReader );
StringWriter buffer = new StringWriter();
OutputFormat format = new OutputFormat();
format.setEncoding("UTF-8");
format.setIndentSize(4);
format.setNewlines(true);
format.setTrimText(true);
format.setExpandEmptyElements(true);
HTMLWriter writer = new HTMLWriter(buffer,format);
writer.write(doc);
String xml = buffer.toString();
System.out.println("xml:"+xml);
} catch (DocumentException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}