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="" 

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(
    new XmlReaderSettings() {
        ValidationType  = ValidationType.Schema, 
        ValidationFlags = 
XPathDocument d = new XPathDocument(r);

Posted on February 15, 2010 from Calgary

Newest Articles


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

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.