Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

.net

xsd.exe

fcl

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.

like image 758
John K Avatar asked Nov 10 '10 23:11

John K


People also ask

What is XSD EXE?

The XML Schema Definition (Xsd.exe) tool generates XML schema or common language runtime classes from XDR, XML, and XSD files, or from classes in a runtime assembly.

What is the use of XSD file in C#?

XSD is a schema language; you use it to define the possible structure and contents of an XML format. A validating parser can then check whether an XML instance document conforms to an XSD schema or a set of schemas.


1 Answers

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();
        }
    }
like image 55
Chris Pont Avatar answered Oct 05 '22 02:10

Chris Pont