|
Use "document.setXMLEncoding" such settings file is still generated xml utf-8 encoding.
OutputFormat need to set the output file encoding format.
Element rootElement = document.addElement ( "data");
document.setXMLEncoding ( "GBK"); // default utf-8
...
public static void writeXMLFile (Document document, File file, String Encoding) {try {OutputFormat format = OutputFormat.createPrettyPrint (); // output do not want to beautify the landscaping can use the new OutputFormat (); format.setEncoding (Encoding.toUpperCase ()); OutputStream out = new FileOutputStream (file); XMLWriter writer = new XMLWriter (out, format); writer.write (document); writer.close ();} catch (IOException e) {e.printStackTrace ();}
Use "OutputFormat", you can set the output file xml encoded and xml file will also change at the statement.
Quote others answer: explain "document.setXMLEncoding" and "format.setEncoding" set difference coding
public class TestXML {@Test public void test () throws IOException {Document doc = new DefaultDocument (); doc.addElement ( "root"); // print out here is the default utf-8 System.out.println (doc. asXML ()); doc.setXMLEncoding ( "utf-16"); // print out here is modified utf-16 System.out.println (doc.asXML ()); // there is no set default encoding format saved is utf-8, look at the source code to know dom4j saveXML (doc, "D: \ temp \ test \ test1.xml", null); // set here so save after encoding format is big5 saveXML (doc, ! "D: \ temp \ test \ test2.xml", "big5");} private void saveXML (Document doc, String filePath, String encode) throws IOException {OutputFormat format = new OutputFormat (); if (null = encode) {format.setEncoding (encode.toUpperCase ());} XMLWriter xmlWriter = new XMLWriter (new FileOutputStream (filePath), format); xmlWriter.write (doc); xmlWriter.flush (); xmlWriter.close ();}}
Finally this:
XMLWriter can pass OutputStream or Writer
XMLWriter writer = new XMLWriter (OutputStream, OutputFormat);
XMLWriter writer = new XMLWriter (Writer, OutputFormat);
Initially tried to pass a new FileWriter (file), as follows
try {
XMLWriter writer = new XMLWriter (new FileWriter (f), format);
writer.write (document);
writer.close ();
result = fileName;
} Catch (IOException e) {// TODO Auto-generated catch block
e.printStackTrace ();
}
But the result is not right. Modified as follows, the results are correct.
try {
OutputFormat format = OutputFormat.createPrettyPrint ();
XMLWriter xmlWriter = new XMLWriter (new FileOutputStream (f), format);
xmlWriter.write (document);
xmlWriter.flush ();
xmlWriter.close ();
result = fileName;
} Catch (IOException e) {// TODO Auto-generated catch block
e.printStackTrace ();
LOG.error ( "trans for XML error:", e);
}
Record. |
|
|
|