【发布时间】:2012-08-06 17:38:45
【问题描述】:
我构建了一个小程序,它从 Google Maps API 地理编码服务读取 XML 输出并使用 LINQ to XML 解析字符串。
如果返回的 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;
}
【问题讨论】:
-
您的代码在哪里“中断”?请提供一些例外信息或类似信息。
-
这是一个编码问题。 stackoverflow.com/questions/4671984/… 的可能重复项
-
@pdriegen:表面上看起来像是编码问题,但错误在哪里?
WebClient.DownloadString从 HTTP 标头中获取字符集,并且应该能够正确解码字符串。 .NET 中的内部字符串未编码,XElement.Parse不必处理字符集。
标签: c# google-maps-api-3 xml-parsing linq-to-xml