根据xsd生成C#类
Posted 晓明的哥哥
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了根据xsd生成C#类相关的知识,希望对你有一定的参考价值。
var file = "1.xsd"; // Get the namespace for the schema. CodeNamespace ns = Processor.Process(file, "Dm"); // Create the appropriate generator for the language. CodeDomProvider provider; if ("cs" == "cs") provider = new Microsoft.CSharp.CSharpCodeProvider(); else if (args[3] == "vb") provider = new Microsoft.VisualBasic.VBCodeProvider(); else throw new ArgumentException("Invalid language", args[3]); // Write the code to the output file. using (StreamWriter sw = new StreamWriter(file, false)) { provider.CreateGenerator().GenerateCodeFromNamespace( ns, sw, new CodeGeneratorOptions()); } Console.WriteLine("Finished"); Console.Read();
Process
public sealed class Processor { public static CodeNamespace Process(string xsdFile, string targetNamespace) { // Load the XmlSchema and its collection. XmlSchema xsd; using (FileStream fs = new FileStream(xsdFile, FileMode.Open)) { xsd = XmlSchema.Read(fs, null); xsd.Compile(null); } XmlSchemas schemas = new XmlSchemas(); schemas.Add(xsd); // Create the importer for these schemas. XmlSchemaImporter importer = new XmlSchemaImporter(schemas); // System.CodeDom namespace for the XmlCodeExporter to put classes in. CodeNamespace ns = new CodeNamespace(targetNamespace); XmlCodeExporter exporter = new XmlCodeExporter(ns); // Iterate schema top-level elements and export code for each. foreach (XmlSchemaElement element in xsd.Elements.Values) { // Import the mapping first. XmlTypeMapping mapping = importer.ImportTypeMapping( element.QualifiedName); // Export the code finally. exporter.ExportTypeMapping(mapping); } return ns; } }
Client
以上是关于根据xsd生成C#类的主要内容,如果未能解决你的问题,请参考以下文章
在不修改 C# XSD 类的情况下向 XML 序列化添加前缀和命名空间