Summary

Validates an XML document against an XML schema (XSD) and outputs the results to the console.

Code (C#)

// Use "Input" editor for the XML code to validate
string xmlCode = Input.Text;

// Use "Output" editor for the XML Schema (XSD) to validate the XML code against
string xsdCode = Output.Text;

using (StringReader xmlStringReader = new StringReader(xmlCode))
using (XmlTextReader xmlTextReader = new XmlTextReader(xmlStringReader))
{
    XmlReaderSettings settings = new XmlReaderSettings() { ValidationType = ValidationType.Schema };
    
    using (StringReader xsdStringReader = new StringReader(xsdCode))
    {
        try
        {
            try
            {
                System.Xml.Schema.XmlSchema xmlSchema = System.Xml.Schema.XmlSchema.Read(xsdStringReader,
                    new System.Xml.Schema.ValidationEventHandler(
                        delegate(object sender, System.Xml.Schema.ValidationEventArgs e)
                        {
                            Console.WriteLine("[XML Schema Validation Error] {0}", e.Message);
                        }
                    ));
                settings.Schemas.Add(xmlSchema);
            }
            catch (XmlException ex)
            {
                Console.WriteLine("[XML Schema Parsing Error] {0}", ex.Message);
                return;
            }
                
            settings.ValidationEventHandler += new System.Xml.Schema.ValidationEventHandler(
                delegate(object sender, System.Xml.Schema.ValidationEventArgs e)
                {
                    Console.WriteLine("[XML Validation Error] {0}", e.Message);
                });
            
            using (XmlReader xmlReader = XmlReader.Create(xmlTextReader, settings))
            {
                while (xmlReader.Read());
                
                if (xmlReader.ReadState == ReadState.EndOfFile)
                    Console.WriteLine("Validation successfully completed!");
            }
        }
        catch (XmlException ex)
        {
            Console.WriteLine(ex.TargetSite);
            Console.WriteLine("[XML Parsing Error] {0}", ex.Message);
        }
        catch (System.Xml.Schema.XmlSchemaException ex)
        {
            Console.WriteLine("[XML Schema Error] {0}", ex.Message);
            System.Windows.Forms.MessageBox.Show(ex.Message);
        }
    }
} 
Input Type: Plain Text, Output Type: Plain Text

Download Project File

File: Validate_XML_against_XSD.dvp (3.45 KB)

To open this file, DataVoila must be installed on your computer. If this is not yet the case, please click here to download the free demo version.