C#使用XDocument提取含不同属性的同名XML元素数据咨询
实现方案
你可以通过LINQ to XML按属性筛选对应节点,按需读取目标值,以下是可直接运行的完整实现:
第一步:引入必要命名空间
using System.Xml.Linq; using System.Linq;
第二步:封装查询方法(或直接编写查询逻辑)
// 加载XML的逻辑保持不变 XmlUrlResolver res = new XmlUrlResolver(); XmlReaderSettings set = new XmlReaderSettings(); set.XmlResolver = res; XDocument doc = XDocument.Load(XmlReader.Create("ftp://ftp.website/file.xml", set)); // 按索引查询最低温方法 int GetTemperatureMinByIndex(XDocument doc, int periodIndex) { var targetPeriod = doc.Descendants("forecast-period") .FirstOrDefault(p => p.Attribute("index")?.Value == periodIndex.ToString()); if (targetPeriod == null) return default; var minTempEle = targetPeriod.Elements("element") .FirstOrDefault(e => e.Attribute("type")?.Value == "air_temperate_minimum"); return int.TryParse(minTempEle?.Value, out int temp) ? temp : default; } // 按索引查询降水概率方法 string GetPrecipitationProbabilityByIndex(XDocument doc, int periodIndex) { var targetPeriod = doc.Descendants("forecast-period") .FirstOrDefault(p => p.Attribute("index")?.Value == periodIndex.ToString()); if (targetPeriod == null) return string.Empty; var probEle = targetPeriod.Elements("text") .FirstOrDefault(e => e.Attribute("type")?.Value == "probability_of_precipitation"); return probEle?.Value ?? string.Empty; }
第三步:调用测试
// 输出10 Console.WriteLine(GetTemperatureMinByIndex(doc, 1)); // 输出20% Console.WriteLine(GetPrecipitationProbabilityByIndex(doc, 3));
优化建议
如果需要频繁查询不同周期的多个指标,建议先把所有周期数据解析为强类型对象存入字典,减少重复遍历XML的开销:
// 定义周期数据模型 public class ForecastPeriod { public int Index { get; set; } public int MinTemperature { get; set; } public int MaxTemperature { get; set; } public string ForecastText { get; set; } public string PrecipitationProbability { get; set; } } // 一次性解析所有数据到字典 Dictionary<int, ForecastPeriod> forecastDict = doc.Descendants("forecast-period") .Select(p => new ForecastPeriod { Index = int.Parse(p.Attribute("index").Value), MinTemperature = int.Parse(p.Elements("element").First(e => e.Attribute("type").Value == "air_temperate_minimum").Value), MaxTemperature = int.Parse(p.Elements("element").First(e => e.Attribute("type").Value == "air_temperate_maximum").Value), ForecastText = p.Elements("text").First(e => e.Attribute("type").Value == "forecast").Value, PrecipitationProbability = p.Elements("text").First(e => e.Attribute("type").Value == "probability_of_precipitation").Value }) .ToDictionary(k => k.Index, v => v); // 后续直接从字典取值,性能更高 Console.WriteLine(forecastDict[1].MinTemperature); // 输出10 Console.WriteLine(forecastDict[3].PrecipitationProbability); // 输出20%
内容的提问来源于stack exchange,提问作者Daniel Davidson
相关产品推荐
相关产品推荐

