Programming XSD from types in C # - Include base class properties in an XSD subclass

I have a situation where we have a base class that is implemented by several subclasses. The base class is used to force subclasses to contain specific properties that the system requires.

In any case, I would like to programmatically generate XSD for subclasses, but I would like the properties of the base class to appear in the XSD subclass, because the base class is used for internal reasons and really would not matter to the client.

For example, at present, if I have:

class Foo { public string Id { get; set; } } class Bar : Foo { public string Name { get; set; } } 

And I ran this 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(); } } 

He will then create an XSD as follows:

 <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 as follows:

 <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?

+4
source share
1 answer

I would be very surprised if I saw that this is possible, as you described simply because for this, it would seem, as a rule, to be interrupted from the point of view of orientation to the object, at least most of the time. For example, if a class uses a type property, then in OO any class extending this type will be allowed.

Collapsing the class hierarchy (this is what you described, if I understood correctly), would make it impossible to correctly create the XSD model. There would be limitations even when trying to do this in terms of XSD refactoring, especially where abstract types or substitution groups are involved (I say generally).

+1
source

All Articles