Monday, June 13, 2011

XML Validation

Its worth documenting this somewhere even though its pretty straight forward.

namespace XmlValidator
{
    using System;
    using System.IO;
    using System.Linq;
    using System.Xml;
    using System.Xml.Linq;
    using System.Xml.Schema;

    public class EasyXmlValidator
    {
        private Action<string> output;

        public EasyXmlValidator(Action<string> outputWriter)
        {
            this.output = outputWriter;
        }

        public bool Verify(string[] schemaFilenames, string xml)
        {
            var schemaSet = new XmlSchemaSet();
            foreach (string schema in schemaFilenames)
            {
                string content = File.ReadAllText(schema);
                XDocument document = XDocument.Parse(content);
                var namespaceElement = document.Root.Attributes("targetNamespace").FirstOrDefault();
                var name = namespaceElement == null ? string.Empty : namespaceElement.Value;
                schemaSet.Add(name, XmlReader.Create(new StringReader(content)));
            }

            XDocument doc1 = XDocument.Parse(xml);

            Console.WriteLine("Validating doc1");
            bool errors = false;
            doc1.Validate(schemaSet, (o, e) =>
            {
                this.output(string.Format("{0}", e.Message));
                errors = true;
            });

            this.output(string.Format("doc1 {0}", errors ? "did not validate" : "validated"));
            return !errors;
        }

        public bool Verify(string schema, string xml)
        {
            return Verify(new[] { schema }, xml);
        }
    }
}

No comments:

Post a Comment