如何根据另一个属性的值选择XML中的属性?

时间:2015-01-24 12:14:00

标签: c# xml linq

目前,我可以在XML文档中选择属性,因为它们是唯一可识别的,如下所示:

XmlDocument weatherData = new XmlDocument();
weatherData.Load(query);

XmlNode channel = weatherData.SelectSingleNode("rss").SelectSingleNode("channel");
XmlNamespaceManager man = new XmlNamespaceManager(weatherData.NameTable);
man.AddNamespace("yweather", "http://xml.weather.yahoo.com/ns/rss/1.0");

town            = channel.SelectSingleNode("yweather:location", man).Attributes["city"].Value;

但是如何从同名节点中选择“text”属性(yweather:forecast)?

<yweather:forecast day="Sat" text="Sunny" code="32"/>
<yweather:forecast day="Sun" text="Partly Cloudy" code="30"/>
<yweather:forecast day="Mon" text="AM Showers" code="39"/>
<yweather:forecast day="Tue" text="Cloudy" code="26"/>
<yweather:forecast day="Wed" text="Cloudy/Wind" code="24"/>

我是否可以使用条件语句来仅选择text属性等于“Mon”的day属性?

1 个答案:

答案 0 :(得分:1)

这样的事情会起作用:

string xml = "YourXml";
XElement doc = XElement.Parse(xml);

var Result = from a in doc.Descendants("yweather:forecast")
             where a.Attribute("day").Value == "Mon"
             select a.Attribute("text").Value;

或lambda语法:

var Result = doc.Descendants("yweather:forecast")
                .Where(x=> x.Attribute("day").Value == "Mon")
                .Select(x=> x.Attribute("text").Value);

您也可以参考此SO post