John K
John K

Reputation: 28869

Programmatically use XSD.exe tool feature (generate schema from class) through .NET Framework classes?

I want to generate an XML Schema based upon a class, just as you can do with the Xsd.exe tool.

E.g. xsd.exe /type: typename /outputdir:c:\ assmeblyname.

Is there a way to do this by using classes in the .NET Framework instead of using the standalone tool?

I'm sure I've seen information about task references or similar - i.e. something programmatic - that can be used in place of some of these standalone utilities, or that some standalone utilities get their features through the FCL or a Microsoft API.

Upvotes: 7

Views: 2129

Answers (2)

Clovis
Clovis

Reputation: 11

do this:

public string GetFullSchema() {

        string @namespace = "yourNamespace";

        var q = from t in Assembly.GetExecutingAssembly().GetTypes()
        where t.IsClass && t.Namespace ==  @namespace
        select t;

        XmlReflectionImporter importer = new XmlReflectionImporter(@namespace);

        XmlSchemas schemas = new XmlSchemas();
        XmlSchemaExporter exporter = new XmlSchemaExporter(schemas);


        foreach (var x in q)
        {
                var map = importer.ImportTypeMapping(x);
                exporter.ExportTypeMapping(map);
        }

        using (MemoryStream ms = new MemoryStream())
        {
           schemas[0].Write(ms);
           ms.Position = 0;
           return new StreamReader(ms).ReadToEnd();
        }

}

Upvotes: 1

Chris Pont
Chris Pont

Reputation: 789

Found this which looks like it should do the trick...

public static string GetSchema<T>()
    {
        XmlAttributeOverrides xao = new XmlAttributeOverrides();
        AttachXmlAttributes(xao, typeof(T));

        XmlReflectionImporter importer = new XmlReflectionImporter(xao);
        XmlSchemas schemas = new XmlSchemas();
        XmlSchemaExporter exporter = new XmlSchemaExporter(schemas);
        XmlTypeMapping map = importer.ImportTypeMapping(typeof(T));
        exporter.ExportTypeMapping(map);

        using (MemoryStream ms = new MemoryStream())
        {
            schemas[0].Write(ms);
            ms.Position = 0;
            return new StreamReader(ms).ReadToEnd();
        }
    }

Upvotes: 1

Related Questions