No difficulty, just on the code.
/** * * @param fileName */public static void Createxmlutf_8 (String filename) {Element root = documenthelper.createelement ("root");D ocument Document = documenthelper.createdocument (root); Element title = root.addelement ("title"), Title.settext ("caption");//Assignment try {//write to file FileWriter fileWriter = new FileWriter ( fileName); OutputFormat format = new OutputFormat (); XMLWriter XMLWriter = new XMLWriter (fileWriter, format); Xmlwriter.write (document); Write to file in Xmlwriter.close ();} catch (IOException e) {System.out.println (E.getmessage ());}} /** * * @param fileName */public static void createXmlGb2312 (String filename) {Element root = Documenthelper.createelemen T ("root");D ocument Document = documenthelper.createdocument (root);d ocument.setxmlencoding ("gb2312"); Element title = root.addelement ("title"); Title.settext ("caption");//Assignment try {//write to file Java.io.Writer wr=new Java.io.OutputStreamWriter (New Java.io.FileOutputStream (FileName), "gb2312"); document.write (WR); Wr.close ();} catch (IOException e) {System.out.priNtln (E.getmessage ());}}
Results:
<?xml version= "1.0" encoding= "UTF-8"?> <root> <title> title </title> </root >
<?xml version= "1.0" encoding= "gb2312"?> <root> <title> title </title> </root >
Java generates XML encoding utf-f, gb2312