The way to test if the element exists is to simply access it and then check if it is Nothing
, like this:
If doc.Element("product").Element("Name") IsNot Nothing Then
' ...
End If
Notice that I used doc.Element("product")
rather than doc.Root.Element("product")
since, in your example XML, product
is the root element. However, using the Element
property like that is dangerous because it will throw an exception if the parent element doesn't exist. In other words, if doc.Element("product")
returns Nothing
, you can't then turn around and access Nothing.Element("Name")
. So, to correct that, you'd have to do something like this:
If (doc.Element("product") IsNot Nothing) AndAlso (doc.Element("product").Element("Name") IsNot Nothing) Then
' ...
End If
But that get's ugly pretty fast. The easier way is to use the .<>
syntax to access the elements, like this:
If doc.<product>.<Name>.FirstOrDefault IsNot Nothing Then
' ...
End If
That will return Nothing
if either product
or Name
does not exist. It will not throw an exception if either or both of them were to be missing. If you did want it to throw an exception, you could still use the .<>
syntax, but just call First
rather than FirstOrDefault
.
Of course, I could point out that all of this would be a bit easier, cleaner, and more flexible if you were to use XPath (the industry standard) rather than Microsoft's proprietary LINQ-to-XML technology, but that would just be petty. Ok, well, I guess it slipped out against my better judgement, so, as long as I've already said it, I might as well give an example:
If doc.XPathSelectElement("/product/Name") IsNot Nothing Then
' ...
End If