Android inputstreamreader parses the XML file encoding problem of GBK and gb2312 encoding.

Source: Internet
Author: User

Android supports three ways to parse XML files: Dom, sax, and pull. I use mostly sax parsing, but I found that by default, Sax only parses UTF-8 encoded XML files;
The solution was finally found through online search:
1. Determine the encoding method of the XML file on the URL resource first.
2. Set the encoding through inputstreamreader, and then pass inputstreamreader to inputsource through the inputsource constructor.
3. When you parse an inputsource resource using sax, it will be parsed according to the specified encoding method.

1. Determine the XML file encoding method on the URL resource, and use a third-party JAR File
// Obtain the detector proxy object
Codepagedetectorproxy detector = codepagedetectorproxy. getinstance ();
// Add a detector to the proxy object
Detector. Add (jchardetfacade. getinstance ());
// Obtain the encoded character set object
Charset = detector. detectcodepage (URL );
// Get the encoding name
String encodingname = charset. Name ();

2. Set the resolution encoding through the inputstreamreader object
Inputsource = NULL;
Inputstream stream = NULL;

// For GBK Encoding
If ("GBK". Equals (encodingutil. checkencoding (URL ))){
Stream = URL. openstream ();
// Use inputstreamreader to set the encoding method
Inputstreamreader streamreader = new inputstreamreader (stream, "GBK ");
Inputsource = new inputsource (streamreader );
} Else {
// UTF-8 encoding
Inputsource = new inputsource (URL. openstream ());
Inputsource. setencoding ("UTF-8 ");
}

3. parse the inputsource object using Sax
Chinanews = saxrssservice. readrssxml (inputsource );
Newsitems = Chinanews. getnewsitems (); inputstreamreader

Related Article

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.