0

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

2 Answers 2

9

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?)

Sign up to request clarification or add additional context in comments.

2 Comments

Even odder that the date has an opening quote and the time has a closing quote.
True - I didn't look beyond the Number element :)
2

I think this should do it.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.