通过.NET Framework类以编程方式使用xsd.exe工具的功能(生成类架构)?架构、方式、功能、工具

2023-09-03 02:41:52 作者:浅安时光

我要生成基于类的XML架构,只是因为你可以 做的 xsd.exe工具。

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

例如。 XSD.EXE /类型:类型名称/ outputdir:C:\ assmeblyname

有没有办法做到这一点的使用类在.NET Framework ,而不是通过独立工具?

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

我敢肯定,我已经看到了有关任务或引用的信息类似 - 即纲领性的东西 - 可以代替其中的一些独立的应用中使用,或一些独立的实用程序通过整箱或微软的API得到他们的特点。

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.

推荐答案

做到这一点:

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();
        }

}