Garbled XML file output by Java

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.