2012-08-09 109 views
1

我已經構建了一個小程序,該程序從Google Maps API地理編碼服務讀取XML輸出並使用LINQ將XML解析爲字符串。從XML中讀取非ASCII字符

如果返回的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; 
       } 
      } 

.....跳過一些聲明代碼。 StateName聲明爲字符串。

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; 
    } 
+2

哪裏代碼「破發」?請提供一些例外信息或類似信息。 – 2012-08-09 13:21:04

+0

這是一個編碼問題。可能的重複http://stackoverflow.com/questions/4671984/parsing-utf8-encoded-data-from-a-web-service – pdriegen 2012-08-09 13:22:23

+0

@pdriegen:表面上看起來像一個編碼問題,但錯誤在哪裏? 'WebClient.DownloadString'從HTTP頭獲取字符集,並且應該能夠正確解碼字符串。 .NET中的內部字符串不會被編碼,「XElement.Parse」不需要處理字符集。 – 2012-08-09 13:31:18

回答

3

我相信Google webservice會返回使用UTF-8編碼的XML。但是,如果HTTP頭中缺少此信息,則WebClient.DownloadString方法將使用Encoding.Default將返回的字節解碼爲字符串。這也被稱爲「ANSI」編碼,在大多數情況下不是UTF-8。

要解決這個問題,你需要在調用之前webclient.DownloadString(request)執行以下任務:

webClient.Encoding = Encoding.UTF8; 
+0

非常感謝! – 2012-08-09 14:40:02