dom4j 生成xml时,属性值中的回车换行问题

首先属性中的回车换行对我来说非常有用,可是在使用过程中发现dom4j自动把回车换行去掉了。
我需要生成的部分xml是这样的。
<data>
@H=16*16
@C=60
我的中国
@I=000
@K=2
@O=000
@Q
</data>
生成xml的部分代码

try {
StringWriter writer = new StringWriter();
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("GB2312");
XMLWriter xmlwriter = new XMLWriter(writer, format);
xmlwriter.write(document);
returnValue = writer.toString();
} catch (Exception ex) {
ex.printStackTrace();
}

用如上代码后生成xml的结果为
<data>@H=16*16 @C=60 我的中国 @I=000 @K=2 @O=000 @Q</data>
证实在生成xml前的代码有回车换行后,详细想“一定是dom4j的问题“
问题就出在OutputFormat.createPrettyPrint();这上。

/**
* A static helper method to create the default pretty printing format. This
* format consists of an indent of 2 spaces, newlines after each element and
* all other whitespace trimmed, and XMTML is false.
*
* @return DOCUMENT ME!
*/
public static OutputFormat createPrettyPrint() {
OutputFormat format = new OutputFormat();
format.setIndentSize(2);
format.setNewlines(true);
format.setTrimText(true);
format.setPadText(true);

return format;
}

/**
* A static helper method to create the default compact format. This format
* does not have any indentation or newlines after an alement and all other
* whitespace trimmed
*
* @return DOCUMENT ME!
*/
public static OutputFormat createCompactFormat() {
OutputFormat format = new OutputFormat();
format.setIndent(false);
format.setNewlines(false);
format.setTrimText(true);

return format;
}
}

createPrettyPrint()方法中有
[color=red]format.setTrimText(true);[/color]
问题就出在这里。
所以新建了类MyOutputFormat 继承了OutputFormat重载了createPrettyPrint()方法

public class MyOutputFormat extends OutputFormat {
public static OutputFormat createPrettyPrint() {
OutputFormat format = new OutputFormat();
format.setIndentSize(2);
format.setNewlines(true);
format.setTrimText(false);
format.setPadText(true);

return format;
}

}

修改后的代码代码

try {
StringWriter writer = new StringWriter();
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("GB2312");
XMLWriter xmlwriter = new XMLWriter(writer, format);
xmlwriter.write(document);
returnValue = writer.toString();
} catch (Exception ex) {
ex.printStackTrace();
}

最后问题解决
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值