-1

I wrote the following code to vaidate an xml file named order.xml

private void ValidateOrderXml()
{
    // Create the XmlSchemaSet class.
    XmlSchemaSet sc = new XmlSchemaSet();

    // Add the schema to the collection.
    sc.Add("urn:order-schema", "order_schema.xsd");

    // Set the validation settings.
    XmlReaderSettings settings = new XmlReaderSettings();
    settings.ValidationType = ValidationType.Schema;
    settings.Schemas.Add(sc);
    settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);

    // Create the XmlReader object.
    XmlReader reader = XmlReader.Create(xmlFileName, settings);

    // Parse the file.  
    try
    {
        while (reader.Read()) ;
    }
    catch (XmlException err)
    {
        ;
    }
    finally
    {
        reader.Close();
    }
}

// Display any validation errors. 
private static void ValidationCallBack(object sender, ValidationEventArgs e)
{
    Console.WriteLine("Validation Error: {0}", e.Message);
}

But the problem is the code does not give any error even if the xml file is invalid. For example,according to schema, the root node should have name orders. I used an xml file with some other root name. Still it validated.

Ondrej Janacek
  • 12,486
  • 14
  • 59
  • 93
Avinash
  • 385
  • 3
  • 11
  • 26

1 Answers1

1

The problem is that you "swallow" the exception:

    // Parse the file.  
    try
    {
        while (reader.Read()) ;
    }
    catch (XmlException err)
    {
        ;
    }
    finally
    {
        reader.Close();
    }
}

So every XmlException that is kept simply disappears because you do not handle this in your catch block:

catch (XmlException err)
{
    ; // you should place your error handling logic here
}

Depending on how you want to handle the exception you could for example log your exception message in a logger and then rethrow it upper. So for example you could throw a new exception with your XmlException as an inner exception:

catch (XmlException err)
{
    //TODO: log your exception message in a logger
    throw new Exception("Xml has not been validated appropriately", err); 
}

Or you could simply rethrow the original exception:

catch (XmlException err)
{
    //TODO: log your exception message in a logger
    throw;
}

Remember that you should never do this:

catch (XmlException err)
{
    //TODO: log your exception message in a logger
    throw err; // <-- DON'T DO THIS!
}

Because it throws the original exception but resets the stack trace, destroying all stack trace information until your catch block :/

Paweł Bejger
  • 6,176
  • 21
  • 26