Milan Tripathi
Milan Tripathi

Reputation: 13

How to get all the exception references from the try block?

I have a method that validates XML against XSD in which I try to pass multiple records. While handling exceptions I receive only first occurred exception as a message. how to get all the error references ?

    public static bool Validate(string sFileXML, string sFileXSD)
    {
        try
        {
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.Schemas.Add(null, sFileXSD);
            settings.ValidationType = ValidationType.Schema;
            XmlDocument document = new XmlDocument();
            document.Load(sFileXML);
            XmlReader objReader = XmlReader.Create(new StringReader(document.InnerXml), settings);
            while (objReader.Read()) 
            {
            }
            return true;
        }
        catch (Exception eException)
        {
            Console.WriteLine(eException.Message);
            return false;
        }
    }

Upvotes: 0

Views: 65

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460208

I'm not sure if this is what you're looking for, but you could use the Try-Catch in the loop:

public static bool Validate(string sFileXML, string sFileXSD)
{
    XmlReaderSettings settings = new XmlReaderSettings();
    settings.Schemas.Add(null, sFileXSD);
    settings.ValidationType = ValidationType.Schema;
    XmlDocument document = new XmlDocument();
    document.Load(sFileXML);
    XmlReader objReader = XmlReader.Create(new StringReader(document.InnerXml), settings);
    bool success = true, canRead = true;
    while(canRead)
    {
        try
        {
            canRead = objReader.Read();
            // do something else?
        } catch (Exception eException)
        {
            success = false;
            Console.WriteLine(eException.Message);
        }
    }
    return success;
}

Upvotes: 2

Patrick Hofman
Patrick Hofman

Reputation: 157048

You can set the ValidationEventHandler on the XmlReaderSettings. That will give you the opportunity to handle every event and exception on reading the XML.

The ValidationEventArgs has an Exception property which contains the XML validation exception.

Upvotes: 2

Related Questions