I have a situation where we have a base class which several subclasses implement. The base class is used to force subclasses to contain certain properties that the system requires.
Anyways, I’d like to programmatically generate XSDs for the subclasses, but I would like the properties of the base class to appear in the subclass XSD, because the base class is used for internal reasons and wouldn’t really have meaning to the client.
For example, currently if I have:
class Foo {
public string Id { get; set; }
}
class Bar : Foo {
public string Name { get; set; }
}
And I run that through the following code:
private string ExtractXsdFromType()
{
Type type = typeof(Bar);
XmlReflectionImporter importer = new XmlReflectionImporter();
XmlTypeMapping mapping = importer.ImportTypeMapping(type);
XmlSchemas xmlSchemas = new XmlSchemas();
XmlSchemaExporter xmlSchemaExporter = new XmlSchemaExporter(xmlSchemas);
using (var writer = new StringWriter())
{
xmlSchemaExporter.ExportTypeMapping(mapping);
xmlSchemas[0].Write(writer);
return XElement.Parse(writer.ToString()).ToString();
}
}
Then it will produce an XSD like this:
<xs:schema elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="Bar" nillable="true" type="Bar" />
<xs:complexType name="Bar">
<xs:complexContent mixed="false">
<xs:extension base="Foo">
<xs:sequence>
<xs:element minOccurs="0" maxOccurs="1" name="Name" type="xs:string" />
</xs:sequence>
</xs:extension>
</xs:complexContent>
</xs:complexType>
<xs:complexType name="Foo" abstract="true">
<xs:attribute name="Id" type="xs:int" use="required" />
</xs:complexType>
</xs:schema>
But I would like to create an XSD like this:
<xs:schema elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="Bar" nillable="true" type="Bar" />
<xs:complexType name="Bar">
<xs:complexContent mixed="false">
<xs:sequence>
<xs:attribute name="Id" type="xs:int" use="required" />
<xs:element minOccurs="0" maxOccurs="1" name="Name" type="xs:string" />
</xs:sequence>
</xs:complexContent>
</xs:complexType>
</xs:schema>
Does anyone know if this is possible?
I would be extremely surprised to actually see this possible the way you described simply because to do it like so would break things from an Object Orientation perspective, at least most of the time. For example, if a class uses a property of a type, then in OO any class extending that type would be allowed instead.
Collapsing the class hierarchy (which is what you describe if I understood correctly), would make it impossible to correctly create an XSD model. There would be limitations even when trying to do so from an XSD refactoring perspective, particularly where abstract types get involved, or substitution groups (I am talking in general).