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?
To install the XML tools plugin, download the plugin zip file, and extract the contents to where you have installed Notepad++ (such as C:\Program Files\Notepad++). Then restart Notepad++, open the XML file you wish to check, click on the "Plugins" menu at the top, select "XML Tools" and click on "Check XML syntax now."
You can validate your XML documents against XML schemas only; validation against DTDs is not supported. However, although you cannot validate against DTDs, you can insert documents that contain a DOCTYPE or that refer to DTDs.
Schema errors occur where there is a problem with the structure or order of the file, or an invalid character is included. Schema errors prevent the validation being run in full because the file cannot be read. This means that errors cannot be traced to a particular record.
XML documents are validated by the Create method of the XmlReader class. To validate an XML document, construct an XmlReaderSettings object that contains an XML schema definition language (XSD) schema with which to validate the XML document.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With