Is this a .NET Framework error validating XDocument against an XML schema?
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.
XDocument:
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"))
)
);
Validation:
XmlSchemaSet set = new XmlSchemaSet();
set.Add(XmlSchema.Read(File.OpenRead("schema.xsd"), null));
document.Validate(set, (s, e) => validationErrors.Add(e));
Schema:
<xs:include schemaLocation="datatypes.xsd"/>
<xs:element name="root" type="rootType"/>
<xs:complexType name="rootType">
<xs:sequence>
<xs:element name="test" type="ABSTRACT"/>
</xs:sequence>
</xs:complexType>
Datatypes:
<xsd:complexType name="ABSTRACT" abstract="true" />
<xsd:complexType name="BOOLEAN">
<xsd:complexContent>
<xsd:extension base="ABSTRACT">
<xsd:attribute name="value" type="xsd:boolean" use="required"/>
</xsd:extension>
</xsd:complexContent>
</xsd:complexType>
Error:
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).
[...] explain the problem in depth here. There are some code snippets and a sample Visual Studio project of a simple test case which [...]