Marek Buchtela
Marek Buchtela

Reputation: 1003

Checking if element exists in XML file

I need to check if an element in XML file exists. After searching here, I have tried a code from one of very similiar questions I found here, so the code looks like this(it is looped using foreach so it checks every airport in group airports):

string icao = airport.Attributes.GetNamedItem("icao").Value;
            if(airports.SelectSingleNode("/vEsup/airports/airport/" + icao + "/departures")==null)
            {
                MessageBox.Show("I exist!");
            }

Please note that the message box is just for testing, I find it the easiest way to check if the code is working properly. However, I found out that whatever path I enter, it always shows the messagebox, regardless if it exist in the XML file or not.

Upvotes: 1

Views: 2587

Answers (3)

Brian
Brian

Reputation: 5119

In your 'if' block, aren't you checking to see IF the string is null?

My guess - and I could be wrong here - is that you meant:

    string icao = airport.Attributes.GetNamedItem("icao").Value;
        if(airports.SelectSingleNode("/vEsup/airports/airport/" + icao + "/departures")!=null)
        {
            return true;
        }
MessageBox.Show("I exist!");

Upvotes: 0

Gregor Primar
Gregor Primar

Reputation: 6805

You can use Linq to query specific xml nodes and attributes also. Here is link to similar sample: http://www.codearsenal.net/2012/07/c-sharp-load-xml-using-xlinq.html

Upvotes: 2

Alexei Levenkov
Alexei Levenkov

Reputation: 100527

"shows the messagebox if it exist in the XML file or not." seems to be incorrect as you checking for node not to be present in XML if (a.SelectSingleNode(...)==null).

Most likely you need to correctly specify namespaces to you nodes. (need sample XML to give any better suggestion)

Upvotes: 0

Related Questions