我有以下天气 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
作为这个阶段。
预先感谢您的帮助!
最佳答案
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)
是否实际返回了匹配项。
关于c# - 我需要返回匹配变量值的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8961108/