这是使用 Linq to XML 解析响应的方法
实时示例:http://balexandre.com/stackoverflow/7789623/
该链接也包含源代码,但使用 Linq to XML 进行解析非常简单、有趣且极其简单:
private GoogleWheatherInfo parseGoogleWeatherResponse(string url)
{
GoogleWheatherInfo gw = new GoogleWheatherInfo();
// get the XML
XDocument doc = XDocument.Load(url);
// parse data
gw.ForecastInformation = (from x in doc.Descendants("forecast_information")
select new GWForecastInfo
{
City = x.Descendants("city").First().Attribute("data").Value,
PostalCode = x.Descendants("postal_code").First().Attribute("data").Value,
Latitude = long.Parse(string.IsNullOrEmpty(x.Descendants("latitude_e6").First().Attribute("data").Value) ? "0" : x.Descendants("latitude_e6").First().Attribute("data").Value),
Longitude = long.Parse(string.IsNullOrEmpty(x.Descendants("longitude_e6").First().Attribute("data").Value) ? "0" : x.Descendants("longitude_e6").First().Attribute("data").Value),
ForecastDate = DateTime.ParseExact(x.Descendants("forecast_date").First().Attribute("data").Value, "yyyy-MM-dd", CultureInfo.InvariantCulture),
CurrentDate = DateTime.ParseExact(x.Descendants("current_date_time").First().Attribute("data").Value, "yyyy-MM-dd HH:mm:ss K", CultureInfo.InvariantCulture),
UnitSystem = x.Descendants("unit_system").First().Attribute("data").Value
}).Single();
gw.CurrentCondition = (from x in doc.Descendants("current_conditions")
select new GWCurrentCondition
{
Condition = x.Descendants("condition").First().Attribute("data").Value,
TemperatureC = long.Parse(x.Descendants("temp_c").First().Attribute("data").Value),
TemperatureF = long.Parse(x.Descendants("temp_f").First().Attribute("data").Value),
Humidity = x.Descendants("humidity").First().Attribute("data").Value,
Image = x.Descendants("icon").First().Attribute("data").Value,
Wind = x.Descendants("wind_condition").First().Attribute("data").Value
}).Single();
gw.ForecastConditions = (from x in doc.Descendants("forecast_conditions")
select new GWForecastCondition
{
DayOfWeek = x.Descendants("day_of_week").First().Attribute("data").Value,
Low = double.Parse(x.Descendants("low").First().Attribute("data").Value),
High = double.Parse(x.Descendants("high").First().Attribute("data").Value),
Image = x.Descendants("icon").First().Attribute("data").Value,
Condition = x.Descendants("condition").First().Attribute("data").Value,
}).ToList();
return gw;
}
我希望这能让您了解解析任何 XML 文档是多么容易。