我需要返回与变量值匹配的数据

本文关键字:数据 变量值 返回 | 更新日期: 2023-09-27 18:21:16

我有以下天气XML数据:

<weather>
  <current_conditions>
    <condition data="Mostly Cloudy" /> 
    <temp_f data="48" /> 
    <temp_c data="9" /> 
    <humidity data="Humidity: 71%" /> 
    <icon data="/ig/images/weather/mostly_cloudy.gif" /> 
    <wind_condition data="Wind: W at 17 mph" /> 
  </current_conditions>
  <forecast_conditions>
    <day_of_week data="Sun" /> 
    <low data="34" /> 
    <high data="48" /> 
    <icon data="/ig/images/weather/mostly_sunny.gif" /> 
    <condition data="Partly Sunny" /> 
  </forecast_conditions>
  <forecast_conditions>
    <day_of_week data="Mon" /> 
    <low data="32" /> 
    <high data="45" /> 
    <icon data="/ig/images/weather/sunny.gif" /> 
    <condition data="Clear" /> 
  </forecast_conditions>
</weather>

我想返回一个基于日期的字符串,例如,今天:

string theCondition = doc.XPathSelectElement(
  @"weather/current_conditions/condition"
).Attribute("data").Value;

如果我有一个="Sun"的变量,我想返回与上面相同的字符串,但返回<forecast_conditions>,其中<day_of_week data="Sun">,Mon,Tue,Wed也是如此。

如果没有可用的数据,那么我需要Console.WriteLine("no data")

由于我是编程新手,我想在这个阶段继续使用doc.XPathSelectElement。提前感谢您的帮助!

我需要返回与变量值匹配的数据

string day  = "Sun";
string path = "weather/forecast_conditions[day_of_week/@data='" + day + "']/condition";
doc.XPathSelectElement(path).Attribute("data").Value;

请注意,在调用.Attribute("data").Value之前,您需要检查doc.XPathSelectElement(path)是否真的返回了匹配项。

使用

string expr =
   string.Format
    ("string/*/forecast_conditions[day_of_week/@data = '{0}']/condition/@data)", 
      weekDay);
string forcastData = (string) doc.XPathEvaluate(expr);