Wizard
Wizard

Reputation: 11285

c# check elements in xml

How do I check an xml file to determine if some elements exist? For example I have the XML from:

http://www.google.com/ig/api?weather=vilnius&hl=eng

I want check if the word "wind_condition" exists:

if ("wind_condition") {do something}

Upvotes: 0

Views: 701

Answers (4)

McGarnagle
McGarnagle

Reputation: 102783

You can use something like this to query the document, using Linq-to-Xml (untested):

XDocument xdoc = XDocument.Load("http://www.google.com/ig/api?weather=vilnius&hl=eng");
XElement[] myElements = xdoc.Root.Element("weather")
    .Elements()
    .Where(xelement => xelement.Element("wind_condition") != null)
    .ToArray();

Upvotes: 2

Chuck Savage
Chuck Savage

Reputation: 11955

This will determine if the file contains the word wind_condition.

if(xml.ToString().Contains("wind_condition"))
{
    // do something
}

In case you want the element wind_condition

if(xml.Descendants("wind_condition").Count() > 0)
{
    // do something
}

Upvotes: 2

Habib
Habib

Reputation: 223282

Since your root node is xml_api_reply, following should return you a bool whether wind_condition exist or not (I just tested it and it seems to be working)

var result = (from t in loadedData.Descendants("xml_api_reply")
                     select t.Descendants("wind_condition").Any()).Single();

if(result) // equals to if wind_condition exists
{
} 

Upvotes: 2

dubs
dubs

Reputation: 6521

Try:

XmlNodeList list = xml.SelectNodes("//wind_condition");

Then, just check the list returned and process accordingly.

Upvotes: 4

Related Questions