Validating an XML File with an XSD Schema

Posted on 12/15/2006 @ 1:19 PM in #Vanilla .NET by | Feedback | 4875 views

Now we all know that Sharepoint is very XML Centric. I am in the midst of writing an interesting commandline utility that will make managing profiles darned easy. And as you know, once managing user profiles is easy, audience targeting becomes easy - huge benefit.

But that is not what this post is all about. See the issue is, frequently you will write a program that will expect some XML that must meet a certain standard. Usually that validation is done using an XSD Schema, so the Q is, how do you validate an XML file with a given XSD schema?

Here is a little function for your quiver -

public static bool IsXmlValid(string xmlFile, string xmlSchema)

{

    XmlSchemaSet schemaSet = new XmlSchemaSet() ;

    schemaSet.Add("", XmlReader.Create(xmlSchema));

 

    Stream docStream =

new FileStream(xmlFile, FileMode.Open, FileAccess.Read);

    XmlReaderSettings settings = new XmlReaderSettings() ;

    settings.Schemas.Add(schemaSet) ;

    settings.ValidationType = ValidationType.Schema;

    XmlReader xRead = XmlReader.Create(docStream, settings)  ;

 

    bool toReturn = false;

 

    try

    {

        while (xRead.Read())

        {

            // do nothing :-/

        }

        toReturn = true;

    }

    catch (XmlSchemaValidationException xExcp)

    {

        Console.WriteLine(

"Input document " + xmlFile + " does not match the schema", true);

        Console.WriteLine(xExcp.ToString(), true);

    }

    return toReturn;

}

Nice eh?

I'd also recommend reading a quick little modification to the above code, where you can embed the XSD's or other stuff as resources in your dll.

Sound off but keep it civil:

Older comments..


On 12/15/2006 1:21:11 PM Keyvan Nayyeri said ..
I think minor change in code can be good: you can add an event handler for each validation to XmlReaderSettings object by adding your own handler to ValidationEventHandler. This way you can move XmlReader.Reader() to outside of try catch block which makes your code just easier to understand though.

On the other hand, this validation won't work for XML and XSD files from different namespaces.


On 12/15/2006 1:32:28 PM Sahil Malik said ..
Kevin -

Good feedback. I agree on both counts. I was trying to keep it bare and simple :), but yes What I would do is, enhance this into multiple overloads that could optionally accept namespaces. Then you could have a utilities class in your solution somewhere .. blah blah.

BTW - the code above has changed from how it used to be in .NET 1.x.

Sahil


On 12/15/2006 7:06:23 PM Eber Irigoyen said ..
nice, just when I needed it