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

时间:2012-01-22 12:39:57

标签: c# xml xpath

我有以下天气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">同样适用于周一,周二,周三。

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

由于我是编程新手,我希望继续使用doc.XPathSelectElement作为此阶段。 在此先感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

string day  = "Sun";
string path = "weather/forecast_conditions[day_of_week/@data='" + day + "']/condition";

doc.XPathSelectElement(path).Attribute("data").Value;

请注意,在您致电doc.XPathSelectElement(path)之前,您需要检查.Attribute("data").Value是否确实返回了匹配项。

答案 1 :(得分:0)

使用

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

string forcastData = (string) doc.XPathEvaluate(expr);