Chinese garbled characters are mainly caused by conflicts between the two encoding formats:
When Java generates XML, the default encoding method is UTF-8, and the system uses a different encoding method (the encoding used when the system stores files, for example, GBK in windowxp Chinese Version ))
Encoding of XML string output: (unified the encoding methods of the two)
The preceding encoding is used as an example:
Documentbuilderfactory builderfactory = documentbuilderfactory. newinstance (); <br/> documentbuilder bulider = builderfactory. newdocumentbuilder (); <br/> document = bulider. newdocument (); <br/> stringwriter writer = new stringwriter (); <br/> streamresult result = new streamresult (writer ); <br/> domsource xmlsource = new domsource (document); <br/> transformer xformer = transformerfactory. newinstance (). newtransformer (); <br/> string sysencoding = system. getproperty ("file. encoding "); // obtain the System Code <br/> If (sysencoding = NULL | "". equals (sysencoding) <br/> sysencoding = "UTF-8"; <br/> xformer. setoutputproperty ("encoding", sysencoding); // sets the output encoding. <br/> xformer. transform (xmlsource, result); <br/> result. getwriter (). tostring ();
Dom4j reads XML files:
When dom4j reads XML files, the most important thing to note is to set the encoding (to solve Chinese garbled characters ),
For example, convert an XML file to a string:
String filepath = ""; // file path <br/> saxreader reader = new saxreader (); <br/> reader. setencoding ("UTF-8"); // sets the encoding <br/> document DOC = reader. read (new file (filepath); <br/> string xmlstr = Doc. asxml (); // converts a document object to an XML string