Xml Schema as an Embedded Resource

June 17, 2009

Today I ran into an interesting problem trying to validate an XDocument against an XmlSchemaSet.  The complication arose from the fact that the master schema referenced (<import>ed) multiple additional schemas.

Initially I tried copying all the schema files to the output directory, then loading the master schema using XmlReader.Read().  The master schema references other schema files to import  in the format “schema1.xsd“.  By default the XmlReader will automatically try to load all of these referenced schema files when you load the master schema.  However, it will do so by searching for the import path relatively to the path of the currently executing assembly. I.e. not the location which the master schema was read from.  As an aside, this is also a pain to manage cross-project (i.e. a test project testing the implementation project’s validation code — where both projects having different executing assembly paths).

I decided to switch to embedded resources to solve the problem.  The XmlReader.Read() still tried to load the referened schemas by file rather than from embedded resources (dare I say “of course”?).  Fixing this required creating a custom XmlResolver class which overrode the GetEntity method, redirecting requests for schema files to the current manifest.

Now I have a nice neat self-validating implementation assembly with no dependencies on external files/file structure.

Leave a Reply