Simple C# XML Schema Validation

While working I’ve often had to deal with data being sent in XML. Specifically, working on web services which are constantly passing it around. This data usually needs to be marshaled into some domain objects to continue working, but sometimes the data being sent is no good. One solution I found to fail early when encountering bad XML was validating it against it’s schema. I’m not sure if there are simpler ways, but this is how I was able to do it in C#:

public string IsValidXml(string xmlString, string schemaPath)
{
    if (string.IsNullOrWhiteSpace(xmlString))
    {
        throw new ArgumentNullException("xmlString");
    }

    if (string.IsNullOrWhiteSpace(schemaPath))
    {
        throw new ArgumentNullException("schemaPath");
    }

    try
    {
        var settings = new XmlReaderSettings();
        settings.Schemas.Add(null, schemaPath);
        settings.ValidationType = ValidationType.Schema;

        using (var reader = 
               XmlReader.Create(new StringReader(xmlString),
               settings))
        {
            while (reader.Read()) { }
        }

        return string.Empty;
    }
    catch (Exception e)
    {
        if (e.InnerException == null)
        {
            return e.Message;
        }

        return e.Message + " " 
               + e.InnerException.Message;
    }
}

The code above is fairly straight forward. The first two ifs just make sure the arguments coming in are usable, the first is the actual XML string we want to validate and the second is the path or URL to the schema which should be used. Inside the the try catch we scan the string after having added the schema information to the XMLReaderSettings object.

If an error is encountered while reading the XML an exception is thrown and we promptly catch that and return a string with the error. Returning both the exception message and the message from the inner exception yields a better explanation of why we had a failure. Usually the first one tells us the line where it failed and the second the element that caused the failure. Note, however, it is important to check for the InnerException object as it is not always available.  

Leave a Reply

Your email address will not be published. Required fields are marked *

*