关于用dom4j实现xml文件输出时格式设置的发现

来源:互联网 发布:网络防诈骗电话费骗局 编辑:程序博客网 时间:2024/05/01 03:26
昨天在进行萧山校产的报表配置的时候遇到一个问题,我要求输出的xml文件中保留我原来的内容(内容中包括有很多的空格),但是dom4j在输出文件时自动将这些空格去除了,经研究有以下发现:
当我们在用dom4j处理xml文件输出的时候可能会遇到以下的问题,就是我们要求每个element中的text保留我写入的原始信息,比如说空格不能被去除;
比如说我们要输出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());
此时输出的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中的值如果有空格的话在任何情况下是都不会去除空格的;
原创粉丝点击