tags:

views:

291

answers:

2

Please could someone post an example of how to check if an element exists in an xml file using linq?

Here is the xml document:

<Database>
 <SMS>
   <Number>"+447528349828"</Number> 
   <Date>"09/06/24</Date> 
   <Time>13:35:01"</Time> 
   <Message>"Stop"</Message> 
</SMS>
 <SMS>
   <Number>"+447528349828"</Number> 
   <Date>"09/06/24</Date> 
   <Time>13:35:01"</Time> 
   <Message>"Stop"</Message> 
 </SMS>
</Database>

I want to be able to specify a number and check if it exists

+6  A: 

How about:

public static bool HasNumber(XDocument doc, string number)
{
    return doc.Descendants("Number")
              .Any(element => element.Value == number);
}

(One point to note - it looks a bit odd that you've got quotes round the numbers in the XML file. Do you have to have them?)

Jon Skeet
Even odder that the date has an opening quote and the time has a closing quote.
Dennis Palmer
True - I didn't look beyond the Number element :)
Jon Skeet
Old example xml doc - been sanitized now cheers
Goober
+2  A: 

I think this should do it.

var exists = xml.Descendants("Number")
                .Any(e => String.Equals(
                   (string)e, 
                   number, 
                   StringComparison.OrdinalIgnoreCase))
Talljoe