crmepham
crmepham

Reputation: 4760

How to select an attribute in XML based on the value of another attribute?

Currently I am able to select attributes in an XML document because they are uniquely identifiable, like this:

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;

But how do I select the "text" attribute from a node of the same name (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"/>

Is there a conditional statement I can use to only select the text attribute where the day attribute is equal to "Mon"?

Upvotes: 0

Views: 791

Answers (1)

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62498

Something like this will work:

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;

or lambda syntax:

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

you can also refer this SO post

Upvotes: 1

Related Questions