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

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

Java代码    收藏代码
  1. try {  
  2.     StringWriter writer = new StringWriter();  
  3.     OutputFormat format = OutputFormat.createPrettyPrint();  
  4.     format.setEncoding("GB2312");  
  5.     XMLWriter xmlwriter = new XMLWriter(writer, format);  
  6.     xmlwriter.write(document);  
  7.     returnValue = writer.toString();  
  8.      } catch (Exception ex) {  
  9.        ex.printStackTrace();  
  10.    }  


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

Java代码    收藏代码
  1. /** 
  2.     * A static helper method to create the default pretty printing format. This 
  3.     * format consists of an indent of 2 spaces, newlines after each element and 
  4.     * all other whitespace trimmed, and XMTML is false. 
  5.     *  
  6.     * @return DOCUMENT ME! 
  7.     */  
  8.    public static OutputFormat createPrettyPrint() {  
  9.        OutputFormat format = new OutputFormat();  
  10.        format.setIndentSize(2);  
  11.        format.setNewlines(true);  
  12.        format.setTrimText(true);  
  13.        format.setPadText(true);  
  14.   
  15.        return format;  
  16.    }  
  17.   
  18.    /** 
  19.     * A static helper method to create the default compact format. This format 
  20.     * does not have any indentation or newlines after an alement and all other 
  21.     * whitespace trimmed 
  22.     *  
  23.     * @return DOCUMENT ME! 
  24.     */  
  25.    public static OutputFormat createCompactFormat() {  
  26.        OutputFormat format = new OutputFormat();  
  27.        format.setIndent(false);  
  28.        format.setNewlines(false);  
  29.        format.setTrimText(true);  
  30.   
  31.        return format;  
  32.    }  


createPrettyPrint()方法中有 
format.setTrimText(true); 
问题就出在这里。

format.setTrimText(false); 即可

OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("utf-8");// 设置XML文件的编码格式
        format.setLineSeparator("\n");
        format.setTrimText(false);
        format.setIndent("	");
		Document doc = DocumentHelper.createDocument();

猜你喜欢

转载自tdcq.iteye.com/blog/1893540
今日推荐