dom4j UTF-8編碼的解決

這幾天開始學習dom4j,在網上找了篇文章就開幹了,上手非常的快,但是發現了個問題就是無法以UTF-8保存xml文件,保存後再次讀出的時候會報“Invalid byte 2 of 2-byte UTF-8 sequence.”這樣一個錯誤,檢查發現由dom4j生成的這個文件,在使用可正確處理XML編碼的任何的編輯器中中文成亂碼,從記事本查看並不會出現亂碼會正確顯示中文。讓我很是頭痛。試着使用GBK、gb2312編碼來生成的xml文件卻可以正常的被解析。因此懷疑的dom4j沒有對utf-8編碼進行處理。便開始查看dom4j的源碼。終於發現的問題所在,是自己程序的問題。    在dom4j的範例和網上流行的《DOM4J 使用簡介》這篇教程中新建一個xml文檔的代碼都類似如下 :

    public void createXML(String fileName) {  
        Document doc = org.dom4j.DocumentHelper.createDocument();  
        Element root = doc.addElement("book");  
        root.addAttribute("name", "我的圖書");    
        Element childTmp;  
        childTmp = root.addElement("price");  
        childTmp.setText("21.22");    
        Element writer = root.addElement("author");  
        writer.setText("李四");  
        writer.addAttribute("ID", "001");    
        try {  
            org.dom4j.io.XMLWriter xmlWriter = new org.dom4j.io.XMLWriter(  
                    new FileWriter(fileName));  
            xmlWriter.write(doc); 
            xmlWriter.close();          }  
        catch (Exception e) {  
            System.out.println(e);          }      }  

   在上面的代碼中輸出使用的是FileWriter對象進行文件的輸出。這就是不能正確進行文件編碼的原因所在,java中由Writer類繼承下來的子類沒有提供編碼格式處理,所以dom4j也就無法對輸出的文件進行正確的格式處理。這時候所保存的文件會以系統的默認編碼對文件進行保存,在中文版的window下java的默認的編碼爲GBK,也就是所雖然我們標識了要將xml保存爲utf-8格式但實際上文件是以GBK格式來保存的,所以這也就是爲什麼能夠我們使用GBK、GB2312編碼來生成xml文件能正確的被解析,而以UTF-8格式生成的文件不能被xml解析器所解析的原因。 
   好了現在我們找到了原因所在了,我們來找解決辦法吧。首先我們看看dom4j是如何實現編碼處理的   

   public XMLWriter(OutputStream out) throws UnsupportedEncodingException {  
        //System.out.println("In OutputStream");  
        this.format = DEFAULT_FORMAT;  
        this.writer = createWriter(out, format.getEncoding());  
        this.autoFlush = true;  
       namespaceStack.push(Namespace.NO_NAMESPACE);      }    
    public XMLWriter(OutputStream  out,  OutputFormat  format) 
throws 
UnsupportedEncodingException { 
 
        //System.out.println("In OutputStream,OutputFormat"); 

        this.format = format;  
        this.writer = createWriter(out, format.getEncoding());  
        this.autoFlush = true;  
       namespaceStack.push(Namespace.NO_NAMESPACE);      }         /**  
     * Get an OutputStreamWriter, use preferred encoding.       */  
    protected Writer createWriter(OutputStream outStream, String encoding) throws UnsupportedEncodingException {  
        return new BufferedWriter(  
            new OutputStreamWriter( outStream, encoding )  
        );      }  
   由上面的代碼我們可以看出dom4j對編碼並沒有進行什麼很複雜的處理,完全通過java本身的功能來完成。所以我們在使用dom4j的來生成我們的XML文件時不應該直接爲在構建XMLWriter時,不應該直接爲其賦一個Writer對象,而應該通過一個OutputStream的子類對象來構建。也就是說在我們上面的代碼中,不應該用FileWriter對象來構建xml文檔,而應該使用FileOutputStream對象來構建所以將代碼修改入下:     public void createXML(String fileName) {  
        Document doc = org.dom4j.DocumentHelper.createDocument();  
        Element root = doc.addElement("book");  
        root.addAttribute("name", "我的圖書");  
        Element childTmp;  
        childTmp = root.addElement("price");  
        childTmp.setText("21.22");    
        Element writer = root.addElement("author");  
        writer.setText("李四");  
        writer.addAttribute("ID", "001");    
        try { 
            //注意這裏的修改   
            org.dom4j.io.XMLWriter xmlWriter = new org.dom4j.io.XMLWriter(  
                    new FileOutputStream(fileName));  
            xmlWriter.write(doc);  
            xmlWriter.close();          }  
        catch (Exception e) {  
            System.out.println(e);          }      }    

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章