C# 从XML读取非ASCII字符

C# 从XML读取非ASCII字符,c#,google-maps-api-3,xml-parsing,linq-to-xml,C#,Google Maps Api 3,Xml Parsing,Linq To Xml,我已经构建了一个小程序,它读取GoogleMapsAPI地理代码服务的XML输出,并使用LINQtoXML解析字符串 如果返回的XML包含非ASCII字符,则我的输出似乎中断。有没有办法以不同的方式读取/编码 下面是代码关键部分的快照 public static void Read(IList<string> LocationDetails, string Type) { using (WebClient webClient = new WebClie

我已经构建了一个小程序,它读取GoogleMapsAPI地理代码服务的XML输出,并使用LINQtoXML解析字符串

如果返回的XML包含非ASCII字符,则我的输出似乎中断。有没有办法以不同的方式读取/编码

下面是代码关键部分的快照

    public static void Read(IList<string> LocationDetails, string Type)
    {
        using (WebClient webClient = new WebClient())
        {
            webClient.Proxy = null;

            for(int i = 0; i < 5; i++)
            {
                //Generate geocode request and read XML file to string
                string request = String.Format("Https://maps.google.com/maps/api/geocode/xml?{0}={1}&sensor=false", Type, LocationDetails[i]);
                string locationXML = webClient.DownloadString(request);
                XElement root = XElement.Parse(locationXML);

              //Check if request is OK or otherwise
              if (root.Element("status").Value != "OK")
              {     //Skip to next iteration if status not OK
                 continue;   
              }
            }

我相信GoogleWebService将返回使用UTF-8编码的XML。但是,如果HTTP头中没有此信息,
WebClient.DownloadString
方法将使用
Encoding.Default
将返回的字节解码为字符串。这也称为“ANSI”编码,在大多数情况下不是UTF-8

要解决此问题,您需要在调用
webclient.DownloadString(请求)
之前执行以下分配:


你的代码在哪里“中断”?请提供一些异常信息或类似信息。这是一个编码问题。@pdriegen的可能重复:表面上看起来像是编码问题,但bug在哪里
WebClient.DownloadString
从HTTP头获取字符集,应该能够正确解码字符串。NET中的内部字符串不进行编码,
XElement.Parse
不必处理字符集。
    try
    {
        StateName = (result.Elements("address_component")
         .Where(x => (string)x.Element("type") == "administrative_area_level_1")
         .Select(x => x.Element("long_name").Value).First());
    }
    catch (InvalidOperationException e)
    {
        StateName = null;
    }
webClient.Encoding = Encoding.UTF8;