# Wednesday, June 03, 2009
I know, .NET 3.5 framework will soon became "old" framework, because .NET 4.0 is due to release. Anyway it is still the latest, and today we will look how to validate good old XML document with a given XML schema.

It the old days a XML validation took quite some code. For better understanding what I mean, look an XML validation article on CodeProject.

Now just look at this beauty:
        public bool CheckXmlAgainstGivenSchema(XmlHolder xmlHolder)
        {
            XDocument xmlDocument = XDocument.Parse(xmlHolder.XmlDocument);

            XmlSchemaSet xmlSchemaSet = new XmlSchemaSet();
            xmlSchemaSet.Add("myNamespace", XmlReader.Create(new StringReader(xmlHolder.XmlSchema)));

            bool isValid = true;
            xmlDocument.Validate(xmlSchemaSet, (obj, eventArgs) => { isValid = false; });

            return isValid;
        }
It is interesting that this small code snippet represent a lot of .NET 3.5 technology (LINQ to XML, Extension methods and Lamda expressions). This just show us how useful are those "new" concepts.

First we use XML manipulation class "XDocument", which allow us a really nice and smooth XML manipulation, compare to old XmlDocument. XDocument class have nice feature called "Validate", which turns out that this is just we have needed. :)

Validate method in an framework extension method and all it need is XML Schema, as you would expect of course and an event handler, which handle the situation if XML validation is failed.

We pass XML Schema as "XmlSchemaSet", this type is some kind of collection of the schemas. Validator just looks for a proper schema based on proper namespace and XML document elements. A passing delegate is nicely solved with lambda expression. Instead of it we could declare event handler and pass just a method reference (delegate).

posted on Wednesday, June 03, 2009 6:05:08 PM (Central European Daylight Time, UTC+02:00)  #    Comments [0] Trackback