You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

XML解析类型错误:如何按LocationId获取Location元素与Temperature数据

问题解决方案

1. 按LocationId检索对应城市的Forecast列表

你的原代码出错是因为Forecast的父元素是LocationData,而LocationId在Location下的LocationMetaData节点里,路径指向错误导致结果不符合预期。正确的做法是先定位到目标Location节点,再提取其下的所有Forecast:

方法一:分步查询

// 假设xmlFile是已加载的XDocument实例
// 先找到LocationId=4的Location节点
var targetLocation = xmlFile.Descendants("Location")
    .FirstOrDefault(location => 
        (int)location.Element("LocationMetaData").Element("LocationId") == 4);

// 确认找到节点后,提取所有Forecast元素
if (targetLocation != null)
{
    IEnumerable<XElement> forecastList = targetLocation.Descendants("Forecast");
    // forecastList即为该城市所有6小时预报的XElement集合
}

方法二:链式LINQ查询

如果需要直接获取Forecast集合,可使用SelectMany直接展开:

IEnumerable<XElement> forecastList = xmlFile.Descendants("Location")
    .Where(location => (int)location.Element("LocationMetaData").Element("LocationId") == 4)
    .SelectMany(location => location.Descendants("Forecast"));

2. 从Forecast列表提取Temperature等数据元素

拿到Forecast集合后,通过Element()方法定位目标节点,再转换为对应数据类型即可:

遍历提取单条数据

foreach (var forecast in forecastList)
{
    // 获取预报时间
    string forecastTime = forecast.Element("ForecastTime").Value;
    // 获取温度(转为int类型)
    int temperature = (int)forecast.Element("Temperature");
    // 获取体感温度
    int feelsLike = (int)forecast.Element("FeelsLike");
    
    // 示例输出
    Console.WriteLine($"[{forecastTime}] 温度:{temperature}℃,体感温度:{feelsLike}℃");
}

批量提取为结构化数据

如果需要将数据整理为对象集合方便后续处理:

var forecastData = forecastList.Select(forecast => new {
    ForecastTime = forecast.Element("ForecastTime").Value,
    Temperature = (int)forecast.Element("Temperature"),
    RelativeHumidity = (int)forecast.Element("RelativeHumidity"),
    UVIndex = (int)forecast.Element("UVIndex")
}).ToList();

// forecastData为包含所有预报字段的匿名对象列表

内容的提问来源于stack exchange,提问作者george

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 23:18:26