c# - LINQ to XML: handling nodes that do not exist? -
This can be an easy fix (well, this is probably) but for some reason I can not understand it.
So, I have some XML that looks like this:
excelment xml = excelment.paras (@ "lift; alphabetic & gt; & lt; a Name = "A" /> gt; & lt; ename = "e" /> gt; ; / Alphabet & gt; ");
Then in my code, I refer to a node that can be present or not there:
var name = (From xml to b. Select desecendants ("c") b.Attribute ("name")). FirstOrDefault () Value;
But when it is not in existence, instead of the empty space or "" this one tap reference throws an exception: the object reference is not set for an example of an object.
What is the best way to check and see if a node in my Linux query actually exists? Or do I need to see if it exists in any other way?
Well, you are selecting the attribute - so just use:
< Pre> var nameAttribute = xml.Descendants ("c"). Select (b = & gt; b.Attribute ("name")). FirstOrDefault (); If (nameAttribute! = Null) {string name = nameAttribute.Value; } And {// whatever ...}
(I have replaced it with a query expression because the notation was trivial - the query expression syntax was not actually buying anything to you .)
A problem with this solution: It does not distinguish between the "C" element, but it does not have the "name" attribute, and in the first place there is no "C" element. Do you need to be able to tell the difference?
Comments
Post a Comment