Validate XML According to Schema Location Hints

For those of us unfortunate enough to still be writing XML documents, it’s fairly common practice to “hint” at the location of an XSD schema for a document using attributes in its root node:

<?xml version="1.0" encoding="utf-8" ?>

<root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
      xsi:noNamespaceSchemaLocation="file:Schema.xsd">
    ...
</root>

While working with .NET’s XPathDocument in C#, I noticed that when using this class with just a URI string argument, it will not validate against your schema. The following code throws no exception even if your XSD indicates an invalid file:

using System.Xml.XPath;

XPathDocument d = new XPathDocument("path/to/file.xml");

Properly validating your XML involves giving the XPathDocument an XmlReader instance that’s been setup to respect schema location hints:

using System.Xml;
using System.Xml.Schema;
using System.Xml.XPath;

XmlReader r = XmlReader.Create(
    "path/to/file.xml", 
    new XmlReaderSettings() {
        ValidationType  = ValidationType.Schema, 
        ValidationFlags = 
            XmlSchemaValidationFlags.ProcessSchemaLocation, 
    }
);
XPathDocument d = new XPathDocument(r);

Posted on February 15, 2010 from Calgary

About

My name is Brandur. I'm a polyglot software engineer and part-time designer working at Heroku in San Francisco, California. I'm a Canadian expat. My name is Icelandic. Drop me a line at brandur@mutelight.org.

Aside from technology, I'm interested in energy and how it relates to our society, travel, longboarding, muay thai, symphonic metal, and the guitar.

If you liked this article, consider finding me on Twitter.