I spent a large portion of my time yesterday wrestling with validation errors for an XML document – a document which I was positive should be validating correctly. After a lot of fumbling around with options, various incantations of xsi, and checking & rechecking the schema, it occurred to suspect something could be up with the .NET Framework.
Sure enough, I discovered that Visual Studio’s built in XML document schema validation detected no errors in the document I was trying to validate. Furthermore, I discovered that if I wrote out the XDocument to a string first, and then validated that instead of the XDocument directly, there were no validation errors…
I went to work sandboxing the problem and I have now reproduced it in a very simple way. The root of the problem is the validation failing to resolve abstract types from the schema datatypes.
XNamespace rootNs = "testNamespace";
XNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";
XDocument document = new XDocument(
new XElement(rootNs + "root",
new XAttribute(XNamespace.Xmlns + "xsi", xsi.NamespaceName),
new XElement(rootNs + "test",
new XAttribute("value", "true"),
new XAttribute(xsi + "type", "BOOLEAN"))
XmlSchemaSet set = new XmlSchemaSet();
document.Validate(set, (s, e) => validationErrors.Add(e));
<xs:element name="root" type="rootType"/>
<xs:element name="test" type="ABSTRACT"/>
<xsd:complexType name="ABSTRACT" abstract="true" />
<xsd:attribute name="value" type="xsd:boolean" use="required"/>
This is an invalid xsi:type 'BOOLEAN'.
Here is a small Visual Studio 2008 solution which illustrates the problem. You just need to run the solution and it will perform two types of validation on the same document with the same schema – one should succeed and the other should fail. Along with the complete files from which the snippets above are taken, also included in the solution is a sample valid XML file (which should be validated by VS’s inbuilt schema validation).