Rafael Kayser Smiderle
Rafael Kayser Smiderle

Reputation: 690

Get a error list after validate xml against a schema file

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?

Upvotes: 5

Views: 12335

Answers (2)

Prabhakaran Rajagopal
Prabhakaran Rajagopal

Reputation: 703

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);

Upvotes: 3

gitsitgo
gitsitgo

Reputation: 6769

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.

Upvotes: 14

Related Questions