DCSIMG
Validating Xml File Against XSD Schema - Nati Dobkin
Validating Xml File Against XSD Schema

Let the code talk

public class XmlXsdValidator
{
    private static bool _isValied = true;
    public static bool ValidateXmlAgainstXsdSchema(string xmlPath, string xsdPath)
    {
        try
        {
            XmlReader xsd = new XmlTextReader(xsdPath);
            XmlSchemaSet schema = new XmlSchemaSet();
            schema.Add(null, xsd);

            XmlReaderSettings xmlReadeSettings = new XmlReaderSettings();
            xmlReadeSettings.ValidationType = ValidationType.Schema;
            xmlReadeSettings.Schemas.Add(schema);
            xmlReadeSettings.ValidationEventHandler += new ValidationEventHandler(ValidationHandler);

            XmlTextReader xmlTextReader = new XmlTextReader(xmlPath);
            XmlReader xmlReader = XmlReader.Create(xmlTextReader, xmlReadeSettings);

            while(xmlReader.Read());
            xmlReader.Close();
        }
        catch (Exception ex)
        {
            _isValied = false;
            // Write here exception massage to log
        }
        return _isValied;
    }

    private static void ValidationHandler(object sender, ValidationEventArgs args)
    {
        _isValied = false;
    }
}

There is one static method that get XML and XSD paths and return true if the xml fit the xsd schema and false otherwise.

Published Tuesday, February 19, 2008 9:16 PM by Nati Dobkin

Comments

No Comments

Leave a Comment

(required) 
(required) 
(optional)
(required) 

Enter the numbers above: