| Dom 4j 格式化xml補(bǔ)充   作為一個(gè)優(yōu)秀的XML framework的Dom4j,本身提供了格式化文件的一些方法,讓我們看看如何可以更方便的處理。 本文涉及如何格式化xml輸出,設(shè)置輸出字符集,以及XMLWriter不同的writer方法的區(qū)別。   Dom4j提供的格式化xml方法: 
    
        
            | OutputFormat format = OutputFormat.createPrettyPrint();    XMLWriter writer = new XMLWriter( out, format );    writer.write( document );    writer.close();   |    這里創(chuàng)建一個(gè) OutputFormat 類,用來(lái)作為生成XMLWriter的參數(shù)。然后創(chuàng)建XMLWriter,調(diào)用 write 方法輸出 格式化后的 Xml 。   如果你想得到Xml 返回的內(nèi)容,而不是直接輸入到output流里面,可以這樣處理: 
    
        
            |     public static String format(Document document){         StringWriter writer = new StringWriter();                  OutputFormat format = OutputFormat.createPrettyPrint();         format.setEncoding("gb2312");            XMLWriter xmlwriter = new XMLWriter( writer, format );         try {             xmlwriter.write(document);             } catch (Exception e) {             e.printStackTrace();         }                  return writer.toString();     } |    在這里我們創(chuàng)建一個(gè)StringWriter類,把XMLWriter輸出到StringWriter,然后返回Xml的文本內(nèi)容。   在這里也許你會(huì)很奇怪,為什么不用XMLWriter的 write(String text) 方法, 而是采用write(Document doc)方法呢,下面我們可以做一個(gè)試驗(yàn)。  
 使用write(Document doc)的結(jié)果:
 
    
        
            | <?xml version="1.0" encoding="gb2312"?>   <DSTreeRoot text="root根" open="true">   <DsTree text="節(jié)點(diǎn)1" open="true"/>   <DsTree text="節(jié)點(diǎn)2" open="true"/> </DSTreeRoot> |   
 使用write(String text)的結(jié)果:
 
    
        
            | <?xml version="1.0" encoding="UTF-8"?> <DSTreeRoot text="root根" open="true"><DsTree text="節(jié)點(diǎn)1" open="true"/><DsTree text="節(jié)點(diǎn)2" open="true"/></DSTreeRoot> |  |