dom4j处理转义字符,请大家帮忙啊!本帖最后由 untatsu 于 2012-12-11 12:32:35 编辑import org.dom4j.Docum
dom4j处理转义字符,请大家帮忙啊!
本帖最后由 untatsu 于 2012-12-11 12:32:35 编辑
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
public class DOM {
public static void main(String[] args) throws Exception {
Document doc = DocumentHelper.parseText("<root>"</root>");
System.out.println(doc.asXML());
}
}
得到的结果:
<?xml version="1.0" encoding="UTF-8"?>
<root>"</root>
我希望不处理转义字符,能得到:
<?xml version="1.0" encoding="UTF-8"?>
<root>"</root>
不管我从xml里读到,还是用字符串,转义字符都会变,我希望不处理转义字符,这样write到xml文件里也不处理。怎么办呢。
[解决办法]//转码加入xml文件的另一种方法
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("UTF-8");
XMLWriter writer = new XMLWriter(new FileOutputStream("src/book.xml"),format);
writer.write(document);
writer.close();
}
原出处:http://blog.csdn.net/tianyazaiheruan/article/details/8065722
[解决办法]import java.io.IOException;
import java.io.StringWriter;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
public class Test {
public static void main(String[] args) throws Exception {
Document doc = DocumentHelper.createDocument();
doc.setXMLEncoding("GBK");
Element root = doc.addElement("root");
root.addText(""");
//Document doc = DocumentHelper.parseText("<root>"</root>");
System.out.println(doc.asXML());
System.out.println(Test.formatXml(doc, "utf-8", false));
}
/**
* 格式化XML文档
*
* @param document xml文档
* @param charset 字符串的编码
* @param istrans 是否对属性和元素值进行转移
* @return 格式化后XML字符串
*/
public static String formatXml(Document document, String charset, boolean istrans) {
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding(charset);
StringWriter sw = new StringWriter();
XMLWriter xw = new XMLWriter(sw, format);
xw.setEscapeText(istrans);
try {
xw.write(document);
xw.flush();
xw.close();
} catch (IOException e) {
System.out.println("格式化XML文档发生异常,请检查!");
e.printStackTrace();
}
return sw.toString();
}
}