2

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

2 Answers 2

1

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());
2
  • 1
    Marry me? Nah but seriously, just changing that line of code fixed it. Thank you so much haha
    – Anuj Hari
    Aug 12, 2015 at 21:35
  • and also well explained, now i know why it was throwing the exception and how count() actually works :)
    – Anuj Hari
    Aug 12, 2015 at 21:36
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.