c# - 我需要返回匹配变量值的数据

标签 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作为这个阶段。 预先感谢您的帮助!

最佳答案

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/

相关文章:

c# - Mono:是否支持更改线程的优先级?

java - 如何查找/选择以下 Web 元素的 xpath?

xml - XPath:匹配多个 child 之一

python - 如何在 webdriver 中使用 onclick 事件作为选择器?

php - 在 PHP 或 JavaScript 中查询大型 XML 文件(600mb+)?

android - 带有 RecyclerView 的 LinearLayout 在 CardView 外滚动时隐藏 ImageView

c# - 使用静态构造函数(Jon Skeet 脑筋急转弯)

c# - 我应该选择 : This is a full trust application

c# - 在 C# 中,在类中引用成员属性的普遍接受方式是什么?

android - 如何在 BottomNavigationView 中设置指标?