Validating against XSD’s

February 27, 2009 § 2 Comments

The last post about creating XSD’s won’t help you much if you can’t figure out how to validate your XML against an XSD. Obviously, you can put the reference to the XSD into the XML file like this:

<SEASON xmlns="http://www.jamware.net"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.jamware.net/baseball.xsd">

This’ll work fine, obviously, but what if you aren’t in control of the XML file? For instance, you may be getting the file from a third party (customer or vendor) and can’t modify it, yet you still want to verify it against an XSD.

Here’s a utility class you can add to your toolbox. Give the Validate function your XML as a string and your XSD as a string. It could probably use some function overrides to read directly from files, but I’ll leave that as an exercise for the reader. This was enough for my needs.

/// <summary>
/// validates xml
/// </summary>
public class ValidateXml
{
    private List<Exception> validationExceptions;
 
    /// <summary>
    /// Gets or sets the validation exceptions.
    /// </summary>
    /// <value>The validation exceptions.</value>
    public List<Exception> ValidationExceptions
    {
        get { return validationExceptions; }
    }
 
    /// <summary>
    /// Validates the specified XML.
    /// </summary>
    /// <param name="xml">The XML.</param>
    /// <param name="xsd">The XSD.</param>
    public bool Validate(string xml, string xsd)
    {
        validationExceptions = new List<Exception>();
 
        XmlParserContext context = new XmlParserContext(null, new XmlNamespaceManager(new NameTable()), null, XmlSpace.None);
 
        XmlTextReader xmlReader = new XmlTextReader(xml, XmlNodeType.Document, context);
        XmlTextReader xsdReader = new XmlTextReader(xsd, XmlNodeType.Document, context);
 
        XmlReaderSettings readerSettings = new XmlReaderSettings();
        readerSettings.ValidationType = ValidationType.Schema;
        readerSettings.Schemas.Add("", xsdReader);
        readerSettings.ConformanceLevel = ConformanceLevel.Auto;
        XmlReader objValidator = XmlReader.Create(xmlReader, readerSettings);
 
        try
        {
            while (objValidator.Read()) { }
        }
        catch (Exception ex)
        {
            validationExceptions.Add(ex);
        }
        finally
        {
            objValidator.Close();
            xmlReader.Close();
            xsdReader.Close();
        }
 
        return (validationExceptions.Count == 0);
    }
}
Advertisements

Tagged: , ,

§ 2 Responses to Validating against XSD’s

  • Billy says:

    Why a collection of Exceptions? (List) I don’t see how you could ever have more than one exception in that list.

  • mikevallotton says:

    That’s a good point, Billy.

    Something like this might be better:

            while(true)
            {
                try
                {
                    if (!objValidator.Read())
                    {
                        break;
                    }
                }
                catch (Exception ex)
                {
                    validationExceptions.Add(ex);
                }
            }
     
            objValidator.Close();
            xmlReader.Close();
            xsdReader.Close();

    I didn’t test that, though. It might get stuck looping forever.

    You could just change it to return only one exception, which is functionally what it’s doing anyway.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

What’s this?

You are currently reading Validating against XSD’s at Mike Vallotton's Blog.

meta

%d bloggers like this: