xyzio

Validating a XML against XSD schema in C#

leave a comment »

Inputs:

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

Output:

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;
            x.Load(source);

            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 |
            XmlSchemaValidationFlags.ProcessSchemaLocation;

            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:

WordPress.com Logo

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

Google photo

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

Twitter picture

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

Facebook photo

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

Connecting to %s

%d bloggers like this: