在dom4j中实现xml文件输出格式的设置

来源:互联网 发布:linux awk 指定匹配列 编辑:程序博客网 时间:2024/05/22 01:38

本文要说明问题:1.输出格式设置 2.空格保留问题

比如说我们要输出xml文件中的内容为:
<?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编码,没有格式,空格也没有去除,实际上就是一个字符串;其输出如下(此种方式可能会产生编码问题):
<?xml version="1.0" encoding="UTF-8"?>
<root>
<author name="James" location="UK">James Strachan</author>
<author name="Bob" location="US"> 中国 Bob McWhirter </author>
</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());

或者如下写法(推荐):

OutputFormat format=OutputFormat.createPrettyPrint();
//format.setEncoding("");
//f.setIndent(" ");//设置每行前的空格数
//format.setTrimText(false);//保留多余空格
XMLWriter output=new XMLWriter(new FileOutputStream(new File("stu.xml")),format);
output.write(doc);
output.close();

此时输出的xml文件中为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>

如果想要对xml文件的输出格式进行设置,就必须用XMLWriter类,但是我们又需要保留其中的空格,此时我们就需要对format进行设置,也就是加上一句format.setTrimText(false);
这样就可以既保持xml文件的输出格式,也可以保留其中的空格,此时的输出为:
<?xml version="1.0" encoding="gb2312"?>
<root>
<author name="James" location="UK">James Strachan</author>
<author name="Bob" location="US"> 中国 Bob McWhirter </author>
</root>
ps:element中attribute中的值如果有空格的话在任何情况下是都不会去除空格的;


原作者不详,查询来自百度文库

原创粉丝点击