日期:2014-05-20  浏览次数:20678 次

dom4j生成xml,中文乱码,如何解决
我用dom4j创建一个xml,里面有中文乱码
请问要怎么解决呢,xml文件里注释那一样,应该是中文,现在显示乱码

Java code
package com.zjm.xml;

import java.io.File;
import java.io.FileWriter;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

public class createXML {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        createXML xml = new createXML();
        xml.create();
    }
    
    public boolean create() {
        boolean flag = false;
        Document document = null;        //文档
        Element books = null;            //根节点
        Element book = null;            //book节点
        Element text = null;            //text节点
        OutputFormat format = null;
        XMLWriter writer = null;
        
        try {
            document = DocumentHelper.createDocument();
            books = document.addElement("books");
            books.addComment("注释");
            
            book = books.addElement("book");
            book.addAttribute("name", "book1");
            book.addAttribute("show", "true");
            text = book.addElement("text");
            text.setText("text1");
            
            book = books.addElement("book");
            book.addAttribute("name", "book2");
            book.addAttribute("show", "false");
            text = book.addElement("text");
            text.setText("text2");
            
            format = OutputFormat.createPrettyPrint();
            format.setEncoding("GBK");
            //format.setEncoding("UTF-8");    //用utf-8也不行
            
            System.out.println(document.asXML());
            
            writer = new XMLWriter(new FileWriter(new File("E://mytext.xml")), format);
            writer.write(document);
            writer.close();
            
            flag = true;
            
            return flag;
        }
        catch(Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

}



XML code
<?xml version="1.0" encoding="GBK"?>

<books>
  <!--??-->          
  <book name="book1" show="true">
    <text>text1</text>
  </book>
  <book name="book2" show="false">
    <text>text2</text>
  </book>
</books>


------解决方案--------------------
你用其他的工具如记事本、写字板、ultra edit都打开一下看看。

我的环境中format.setEncoding("UTF-8");用ultra edit默认打开是乱码,但记事本、写字板可以正常打开。

format.setEncoding("GBK");用三个软件都打开正常。

中文xp系统。。。