简体   繁体   中英

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}

Try:

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

Then, just check the list returned and process accordingly.

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();

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
}

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
{
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM