依赖:
implementation 'org.dom4j:dom4j:2.1.3'
代码:
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.io.ByteArrayInputStream;
public class JavaMain {
public static void main(String[] args) {
String xml = "<?xml version=\"1.0\" encoding=\"GB2312\"?><Query>123</Query>";
try {
SAXReader reader = new SAXReader();
reader.setEncoding("gb2312");
Document document = reader.read(new ByteArrayInputStream(xml.getBytes("gb2312")));
Element rootElement = document.getRootElement();
String text = rootElement.getText();
System.out.println("text = " + text);
} catch (Exception e) {
e( "xml解析异常,xml = " + xml, e);
}
}
public static void e(String msg) {
System.out.println(msg);
}
public static void e(String msg, Throwable e) {
e(msg);
e.printStackTrace();
}
}
这个代码在IntelliJ中运行是OK的,但是在AndroidStudio中运行却报了异常,百思不得其解,后来看了一下以前学习Dom4J时的笔记才发现,SAXReader不需要设置编码,因为SAXReader在解析xml的时候就能知道用什么编码来解析了(xml文件中包含有编码信息),所以不用设置,于是把这个代码删除:reader.setEncoding("gb2312");,在IntelliJ和AndroidStudio中均可正常运行!那setEncoding()的功能究竟是什么?文档声明如下:
/**
* Sets encoding used for InputSource (null means system default encoding)
*
* @param encoding - is encoding used for InputSource
*/
public void setEncoding(String encoding) {
this.encoding = encoding;
}
字面理解就是用于设置输入源的编码。这么理解的话那我们前面的设置也没问题啊,是Dom4J有Bug?