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

后端 未结 2 1052
情歌与酒
情歌与酒 2021-01-05 08:52

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

2条回答
  •  温柔的废话
    2021-01-05 09:18

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

    public static string GetSchema()
        {
            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();
            }
        }
    

提交回复
热议问题