Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if element exist using a lambda expression in c#?

I've been using a try/catch statement to run through whether or not an element exists when I parse through it. Obviously this isn't the best way of doing it. I've been using LINQ (lambda expressions) for the majority of my parsing, but I just don't know how to detect if an element is there or not.

One big problem with some solutions I found is that they take 3-4 times more code than using the try/catch block, which kind of defeats the purpose.

I would assume the code would look something like this:

if(document.Element("myElement").Exists())
{
   var myValue = document.Element("myElement").Value;
}

I did find this link, but the looping is unecessary in my case as I can guarantee that it will only show up once if it exists. Plus the fact of having to create a dummy element which seems unecessary as well. Doesn't seem like it's the best way (or a good way) of checking. Any ideas?

like image 892
Edward Avatar asked Oct 24 '22 22:10

Edward


1 Answers

XElement e = document.Element("myElement");
if (e != null)
{
    var myValue = e.Value; 
}

http://msdn.microsoft.com/en-us/library/system.xml.linq.xcontainer.element.aspx

"Gets the first (in document order) child element with the specified XName."

"Returns Nothing if there is no element with the specified name."

like image 106
Joe Mancuso Avatar answered Oct 26 '22 21:10

Joe Mancuso