Link to home
Start Free TrialLog in
Avatar of teknovation

asked on

LINQ XML (Empty or missing element) check using C#


I manage to create a method that allows the missing element to return a blank " " which allows the program to continue and not break.

However, this method doesn't seem to handle the linq code that stores a list.

Can someone help me figure this out on how to write a method that will handle this situation?



This is the current code for handling non-list items and it works just fine.
XmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable());
 XDocument xdocument = XDocument.Load(Path + f.ToString());

var AddressName= ElementValueNull(xdocument.XPathSelectElement("//testfile:AddressName", nsmgr));

  public static string ElementValueNull( XElement element)
            if (element != null)
                return element.Value;

            return "";

Open in new window

Here's the code for the list which doesn't seem to work when I wrap the ElementValueNull method around the linq query.
var qty = lineitem.Descendants().Where(x => x.Name.LocalName == "QuantityNumber").Select(e => e.Value).ToList();

Open in new window

Avatar of teknovation


The difference I see is the one that is not working has Descendant query
Avatar of Fernando Soto
The second query will return a List with zero elements if no elements were found. So to find out if it found anything check the qty.Length property and see if it zero.
but the code breaks right at that condition, i wouldnt be able to check the length of qty
And what is the exception it is throwing?
Index was out of range must be non-negative and less than the size of the collection.

Parameter name: index
Hi teknovation;

I can not see how you are getting that exception on this line of code.
var qty = lineitem.Descendants().Where(x => x.Name.LocalName == "QuantityNumber").Select(e => e.Value).ToList();

Open in new window

because if no elements are found in the XML document then the variable qty will have a List object with zero elements. Now if you try to index into qty then you will see that type of exception. Please post the complete code where this line is in.
correct so how do i check if there are no elements and how do  i assign a "" to that varible. My code crashes when i assign it to the console window output
Avatar of Fernando Soto
Fernando Soto
Flag of United States of America image

Link to home
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Yes!!!! Thank you!!!!