How do I programmatically generate an xml schema from a type? How do I programmatically generate an xml schema from a type? xml xml

How do I programmatically generate an xml schema from a type?


I found the accepted answer generated an incorrect schema given some of my attributes. e.g. It ignored custom names for enum values marked with [XmlEnum(Name="Foo")]

I believe this is the correct way (given your using XmlSerializer) and is quite simple too:

var schemas = new XmlSchemas();var exporter = new XmlSchemaExporter(schemas);var mapping = new XmlReflectionImporter().ImportTypeMapping(typeof(Person));exporter.ExportTypeMapping(mapping);var schemaWriter = new StringWriter();foreach (XmlSchema schema in schemas){    schema.Write(schemaWriter);}return schemaWriter.ToString();

Code extracted from:http://blogs.msdn.com/b/youssefm/archive/2010/05/13/using-xml-schema-import-and-export-for-xmlserializer.aspx


So this works, I guess it wasn't as ugly as it seemed:

var soapReflectionImporter = new SoapReflectionImporter();var xmlTypeMapping = soapReflectionImporter.ImportTypeMapping(typeof(Person));var xmlSchemas = new XmlSchemas();var xmlSchema = new XmlSchema();xmlSchemas.Add(xmlSchema);var xmlSchemaExporter = new XmlSchemaExporter(xmlSchemas);xmlSchemaExporter.ExportTypeMapping(xmlTypeMapping);

I was still hoping there was a 2 line solution out there, it seems like there should be, thanks for the tip @dtb


EDITJust for kicks, here's the 2 line version (self deprecating humor)

var typeMapping = new SoapReflectionImporter().ImportTypeMapping(typeof(Person));new XmlSchemaExporter(new XmlSchemas { new XmlSchema() }).ExportTypeMapping(typeMapping);


You can programmatically invoke xsd.exe:

  1. Add xsd.exe as assembly reference.
  2. using XsdTool;
  3. Xsd.Main(new[] { "myassembly.dll", "/type:MyNamespace.MyClass" });

You can also use Reflector to look at the XsdTool.Xsd.ExportSchemas method. It uses the public XmlReflectionImporter, XmlSchemas, XmlSchema XmlSchemaExporter and XmlTypeMapping classes to create a schema from .NET types.

Essentially it does this:

var importer = new XmlReflectionImporter();var schemas = new XmlSchemas();var exporter = new XmlSchemaExporter(schemas);var xmlTypeMapping = importer.ImportTypeMapping(typeof(Person));exporter.ExportTypeMapping(xmlTypeMapping);schemas.Compile(..., false);for (var i = 0; i < schemas.Count; i++){    var schema = schemas[i];    schema.Write(...);}                 ↑

You should be able to customize the output by passing a suitable writer to the XmlSchema.Write method.