5

I´m validating a XML file against a schema xsd. So far so good, the code generates a exception in case of failure.

 bool isValid = true; List<string> errorList = new List<string>(); try { XmlReaderSettings settings = new XmlReaderSettings(); settings.Schemas.Add(null, schemaFilePath); settings.ValidationType = ValidationType.Schema; XmlDocument document = new XmlDocument(); document.LoadXml(xml); XmlReader rdr = XmlReader.Create(new StringReader(document.InnerXml), settings); while (rdr.Read()) { } } catch (Exception ex) { errorList.Add(ex.Message); isValid = false; } LogErrors(errorList); return isValid; 

But I need that the code build a list of all errors found in the validate before send it to my log, instead of always show only the first one found.

Any thoughts?

5
  • Your catch does nothing with the error. What is the error you are getting, and why are you not doing anything with it? Commented Aug 7, 2013 at 19:07
  • Why don't you return an Exception instead? And then simply log it, or put is on an array or a list. Commented Aug 7, 2013 at 19:12
  • The exception holds only one error at the time an then exits the verification. I want to store all errors in a list and then return it to be handled. The code above is just an example that I found. Commented Aug 7, 2013 at 19:21
  • "the exception holds..." Where is this exception you speak of? Your catch squashes any exception. Yes it is true that the function will return false when it encounters the first error, but you don't even know what the error is! Commented Aug 7, 2013 at 20:10
  • 2
    It's not that hard to understand what I want to do, but I changed the code. I hope is more understandable now. Commented Aug 7, 2013 at 20:22

2 Answers 2

14

You can use the Validate method with a ValidationEventHandler. you can follow MSDN's way of creating the ValidationEventHandler separately or do it inline if you want.

e.g

 //...Other code above XmlDocument document = new XmlDocument(); document.Load(pathXMLCons); document.Validate((o, e) => { //Do your error logging through e.message }); 

If you don't do this, a XmlSchemaValidationException will be thrown and only that one can be caught.

Sign up to request clarification or add additional context in comments.

1 Comment

Glad the answer helped :)
3

I tried XmlDocument which failed in my case. The below code should work Courtesy: C#5.0 in a nutshell

XDocument doc = XDocument.Load("contosoBooks.xml"); XmlSchemaSet set = new XmlSchemaSet(); set.Add(null, "contosoBooks.xsd"); StringBuilder errors = new StringBuilder(); doc.Validate(set, (sender,args) => { errors.AppendLine(args.Exception.Message); }); Console.WriteLine(errors); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.