通过.NET Framework类以编程方式使用XSD.exe工具功能(从类生成模式)?

Joh*_*n K 7 .net xsd.exe fcl

我想基于类生成XML Schema,就像使用Xsd.exe工具一样.

例如 xsd.exe /type: typename /outputdir:c:\ assmeblyname.

有没有办法通过使用.NET Framework中的类而不是使用独立工具来实现此目的?

我确信我已经看到有关任务引用或类似信息的信息 - 即程序化的东西 - 可用于代替某些独立实用程序,或者某些独立实用程序通过FCL或Microsoft API获取其功能.

小智 1

发现这个看起来应该可以解决问题......

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();
        }
    }
Run Code Online (Sandbox Code Playgroud)