Get a list of errors after checking xml against a schema file

I am checking an XML file against an xsd schema. So far so good, the code throws an 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 the code to create a list of all errors found in the check before sending it to my log, and not always show only the first one found.

Any thoughts?

+4
source share
2 answers

You can use the Validate method with the ValidationEventHandler . you can follow the MSDN method to create the ValidationEventHandler separately or make it inline if you want.

eg

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

If you do not, an XmlSchemaValidationException will be XmlSchemaValidationException , and only that can be caught.

+10
source

I tried an XmlDocument, which failed in my case. The code below should work Provided: 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); 
+1
source

Source: https://habr.com/ru/post/1495821/


All Articles