当我们在用dom4j处理xml文件输出的时候可能会遇到以下的问题,就是我们要求每个element中的text保留我写入的原始信息,比如说空格不能被去除;
比如说我们要输出xml文件中的内容为:
<!-- l version="1.0" encoding="gb2312--><?xml version="1.0" encoding="gb2312"?>
<root>
<author name="James" location="UK">James Strachan</author>
<author name="Bob" location="US"> 中国 Bob McWhirter </author>
</root>
注意author中的内容包括很多的空格;
不妨假设我们已经用以下的方法实现了对上面document的写入:
public Document createDocument() {
Document document = DocumentHelper.createDocument();
Element root = document.addElement( "root" );
Element author1 = root.addElement( "author" )
.addAttribute( "name", "James" )
.addAttribute( "location", "UK" )
.addText( "James Strachan" );
Element author2 = root.addElement( "author" )
.addAttribute( "name", "Bob" )
.addAttribute( "location", "US" )
.addText( " 中国 Bob McWhirter " );
return document;
}
dom4j中把document直接或者任意的node写入xml文件时有两种方式:
1、这也是最简单的方法:直接通过write方法输出,如下:
FileWriter fw = new FileWriter("test.xml");
document.write(fw);
此时输出的xml文件中为默认的UTF-8编码,没有格式,空格也没有去除,实际上就是一个字符串;其输出如下:
<!-- l version="1.0" encoding="UTF-8--><?xml version="1.0" encoding="UTF-8"?>
<root>
2、用XMLWriter类中的write方法,此时可以自行设置输出格式,比如紧凑型、缩减型:
OutputFormat format = OutputFormat.createPrettyPrint();//缩减型格式
//OutputFormat format = OutputFormat.createCompactFormat();//紧凑型格式
format.setEncoding("gb2312");//设置编码
//format.setTrimText(false);//设置text中是否要删除其中多余的空格
XMLWriter xw=new XMLWriter(fw,format);
xw.write(dom.createDocument());
此时输出的xml文件中为gb2312编码,缩减型格式,但是多余的空格已经被清除:
<?xml version="1.0" encoding="gb2312"?>
<author name="James" location="UK">James Strachan</author>
<author name="Bob" location="US">中国 Bob McWhirter</author>
</root>
这样就可以既保持xml文件的输出格式,也可以保留其中的空格,此时的输出为:
<?xml version="1.0" encoding="gb2312"?>
<author name="James" location="UK">James Strachan</author>
<author name="Bob" location="US"> 中国 Bob McWhirter </author>
</root>