Anuj Hari
Anuj Hari

Reputation: 543

Working with null elements in an xml

I am currently working on a data import application on VS2012 which takes XML data and imports it into a database. I have a set xsd schema which the xml document must match against.

Within my xsd, I defined the <Loan> to have minOccurs=0, which obviously means that the Loan element doesn't have to be set.

Now when I'm working with my dummy data and put no (and it's other elements inside), it returns to me with an error saying value can not be null. I traced this back to my C# code and found that the line it was failing on was:

int loan_count = fam.Family[i].Loan.Count();

Even though I have minOccurs set to 0, the Loan element still doesn't allow null values.

Is there anyway to make sure that when there is no <Loan> element, the code above returns 0, not Null.

FIXED! ANSWER IS THE ACCEPTED ANSWER

Upvotes: 2

Views: 77

Answers (2)

dbc
dbc

Reputation: 116516

Your problem has nothing to do with XML or your Loan element per se. You appear to be using the Linq extension method Enumerable.Count<TSource>(this IEnumerable<TSource> source) to count the number of loans. This method intentionally throws an ArgumentNullException if the input sequence is null. (I believe all Linq extension methods throw on a null input enumerable.) To work around this, you could make your own extension method to replace Count(), or just do

int loan_count = (fam.Family[i].Loan == null ? 0 : fam.Family[i].Loan.Count());

Upvotes: 1

PhillipH
PhillipH

Reputation: 6202

MinOccurs=0 means you have to pass a value. That value might, or might not, allow a Null; depending on that elements nillable setting. It can legitimately be "MinOccurs=0" and "Nillable=false" which means you don't have to pass a value, but if you do, it cannot be Nil. If you have a Null value, and you need to comply with the XSD, just don't pass the value.

Upvotes: 0

Related Questions