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