Validating a XML against XSD schema in C#

leave a comment »


xmlFileName: Input XML file name
schemaFileName: Input XSD file name


results: Results output

using System.Xml;
using System.Xml.Schema;
using System.IO;

static List<string> results = new List<string>();

        static void Validate(string xmlFileName, string schemaFileName)
            XmlDocument x = new XmlDocument();
            string source = xmlFileName;

            XmlReaderSettings settings = new XmlReaderSettings();
            settings.CloseInput = true;
            settings.ValidationEventHandler += Handler;

            settings.ValidationType = ValidationType.Schema;
            settings.Schemas.Add(null, schemaFileName);
            settings.ValidationFlags =
                 XmlSchemaValidationFlags.ReportValidationWarnings |
            XmlSchemaValidationFlags.ProcessIdentityConstraints |
            XmlSchemaValidationFlags.ProcessInlineSchema |

            StringReader r;
            using (StreamReader sr = new StreamReader(source))
                r = new StringReader(sr.ReadToEnd());

            using (XmlReader validatingReader = XmlReader.Create(r, settings))
                while (validatingReader.Read()) { /* just loop through document */ }

        private static void Handler(object sender, ValidationEventArgs e)
            if (e.Severity == XmlSeverityType.Error || e.Severity == XmlSeverityType.Warning)
                results.Add(String.Format("Line: {0}, Position: {1} "{2}"", e.Exception.LineNumber, e.Exception.LinePosition, e.Exception.Message));

Written by M Kapoor

September 30, 2014 at 3:21 pm

Posted in c#

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: