I have a problem. In my app i download XML file from the Web. Its encoding is ISO-8859-2. I put some data from this XML to Spinner and there are questions marks instead of some polish characters. Have I to change encoding to UTF-8 to solve that problem? If yes, how to do it? I tried using method found on the Internet but it doesn't help
private XmlDocument ChangeXmlEncoding(XmlDocument xmlDoc, string newEncoding)
{
if (xmlDoc.FirstChild.NodeType == XmlNodeType.XmlDeclaration)
{
XmlDeclaration xmlDeclaration = (XmlDeclaration)xmlDoc.FirstChild;
xmlDeclaration.Encoding = newEncoding;
}
return xmlDoc;
}
public static string GetPageAsString(System.Uri address)
{
string result = "";
// Create the web request
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
// Read the whole contents and return as a string
result = reader.ReadToEnd();
}
return result;
}
and usage:
System.Uri uri = new System.Uri("http://nbp.pl/kursy/xml/LastA.xml");
XMLString = GetPageAsString(uri);
dokument = new XmlDocument ();
dokument.LoadXml(XMLString);
dokument = ChangeXmlEncoding(dokument,"utf-8");
Your GetPageAsString
method is broken, basically - it's assuming that the encoding is UTF-8, as that's what StreamReader
uses by default.
I would strongly urge you to avoid performing the string decoding yourself. In order of preference (best first), I would:
XDocument.Load(uri.ToString())
XmlDocument.Load(uri.ToString())
XmlDocument.Load(response.GetResponseStream())
in a method to just load the XML instead of loading the content as a stringIn all of these cases, the XML parser will handle decoding the text from the binary data.
See more on this question at Stackoverflow