百度一圈没找到,还是在StackFlow上找到了答案。
问题描述:Dom4j写入带换行符的属性值时,可以看到生成的XML里是换行的,但是用dom4j读取回来后换行符变成了空格。
解决办法:
1,在XML根节点添加属性
xml:space="preserve"
对应的dom4j代码是:
document.getRootElement().addAttribute(QName.get("space", Namespace.XML_NAMESPACE),
"preserve");
2,需要手动写一个XMLWriter,继承自Dom4j的XMLWriter,重写里面的escapeAttributeEntities方法。
//转义换行符
private static class XmlWriterWithLine extends XMLWriter{
public XmlWriterWithLine(OutputStream out, OutputFormat format)
throws UnsupportedEncodingException {
super(out, format);
}
@Override
protected String escapeAttributeEntities(String text) {
//博客没人气,我已删除此段代码,请各位攻城狮自行研究或留邮箱
}
}
3,最后输出xml
ByteArrayOutputStream baos = new ByteArrayOutputStream();
OutputFormat format = OutputFormat.createPrettyPrint();
format.setIndentSize(4);
format.setNewlines(true);
format.setTrimText(true);
format.setPadText(true);
XMLWriter xw = new XmlWriterWithLine(baos, format);
xw.write(document);
xw.close();
System.out.println(baos.toString("utf-8"));
输出后的换行符变成了 用dom4j读入后直接就是换行符了
上面代码里没有处理\r的情况,读者可以自己查看XmlWriter的源代码