Validating Xml File Against XSD Schema

19 בפברואר 2008

אין תגובות

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.

הוסף תגובה
facebook linkedin twitter email

כתיבת תגובה

האימייל לא יוצג באתר. שדות החובה מסומנים *