public static CodeNamespace Process() { CodeNamespace codeNameSpace = new CodeNamespace("MilkyWay.SolarSystem"); XmlSchemas schemas = new XmlSchemas(); XmlSchema xsd; using (var fs = new FileStream(Path.GetFileName("world.xsd"), FileMode.Open, FileAccess.Read)) { xsd = XmlSchema.Read(fs, null); xsd.Compile(null); schemas.Add(xsd); } XmlSchemaImporter schImporter = new XmlSchemaImporter(schemas); XmlCodeExporter exCode = new XmlCodeExporter(codeNameSpace); foreach (XmlSchemaElement element in xsd.Elements.Values) { var importTypeMapping = schImporter.ImportTypeMapping(element.QualifiedName); exCode.ExportTypeMapping(importTypeMapping); } return(codeNameSpace); }
public static CodeNamespace ProcessXsd(this 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); }
protected override void BeginNamespace() { xmlImporter = new XmlSchemaImporter(LiteralSchemas, ClassNames); soapImporter = new SoapSchemaImporter(EncodedSchemas, ClassNames); xmlExporter = new XmlCodeExporter(CodeNamespace, null); xmlReflectionImporter = new XmlReflectionImporter(); }
/// <summary> /// Generates CodeDom model of the source code based on XML schema. /// </summary> /// <param name="schemas">A set of compiled XML schemas.</param> /// <returns>CodeDom model of the gererated source code.</returns> private CodeCompileUnit GenerateCodeDom(XmlSchemas schemas) { CodeCompileUnit codeCompileUnit = new CodeCompileUnit(); CodeNamespace @namespace = new CodeNamespace(string.Empty); codeCompileUnit.Namespaces.Add(@namespace); CodeGenerationOptions options = CodeGenerationOptions.None; XmlCodeExporter codeExporter = new XmlCodeExporter(@namespace, codeCompileUnit, this.LanguageProvider, options, null); XmlSchemaImporter schemaImporter = new XmlSchemaImporter(schemas, options, this.LanguageProvider, new ImportContext(new CodeIdentifiers(), false)); foreach (XmlSchema schema in schemas) { ImportSchemaAsClasses(schema, schemaImporter, codeExporter, @namespace); } CodeTypeDeclarationCollection types = @namespace.Types; if (types == null || types.Count == 0) { Console.WriteLine("No Classes Generated"); } CodeGenerator.ValidateIdentifiers(@namespace); return(codeCompileUnit); }
protected override void ImportPartsBySchemaElement(QName qname, List <MessagePartDescription> parts, Message msg, MessagePart msgPart) { if (schema_set_cache != schema_set_in_use) { schema_set_cache = schema_set_in_use; var xss = new XmlSchemas(); foreach (XmlSchema xs in schema_set_cache.Schemas()) { xss.Add(xs); } schema_importer = new XmlSchemaImporter(xss); if (ccu.Namespaces.Count == 0) { ccu.Namespaces.Add(new CodeNamespace()); } var cns = ccu.Namespaces [0]; code_exporter = new XmlCodeExporter(cns, ccu); } var part = new MessagePartDescription(qname.Name, qname.Namespace); part.XmlSerializationImporter = this; var mbrNS = msg.ServiceDescription.TargetNamespace; var xmm = schema_importer.ImportMembersMapping(qname); code_exporter.ExportMembersMapping(xmm); // FIXME: use of ElementName is a hack! part.CodeTypeReference = new CodeTypeReference(xmm.ElementName); parts.Add(part); }
protected override void BeginNamespace() { xmlImporter = new XmlSchemaImporter(LiteralSchemas, base.CodeGenerationOptions, base.CodeGenerator, base.ImportContext); soapImporter = new SoapSchemaImporter(EncodedSchemas, base.CodeGenerationOptions, base.CodeGenerator, base.ImportContext); xmlExporter = new XmlCodeExporter(CodeNamespace, null, base.CodeGenerator, base.CodeGenerationOptions, null); soapExporter = new SoapCodeExporter(CodeNamespace, null, base.CodeGenerator, base.CodeGenerationOptions, null); }
private static void Main(string[] args) { XmlSchema rootSchema = GetSchemaFromFile("fpml-main-4-2.xsd"); var schemaSet = new List <XmlSchemaExternal>(); ExtractIncludes(rootSchema, ref schemaSet); var schemas = new XmlSchemas { rootSchema }; schemaSet.ForEach(schemaExternal => schemas.Add(GetSchemaFromFile(schemaExternal.SchemaLocation))); schemas.Compile(null, true); var xmlSchemaImporter = new XmlSchemaImporter(schemas); var codeNamespace = new CodeNamespace("Hosca.FpML4_2"); var xmlCodeExporter = new XmlCodeExporter(codeNamespace); var xmlTypeMappings = new List <XmlTypeMapping>(); foreach (XmlSchemaType schemaType in rootSchema.SchemaTypes.Values) { xmlTypeMappings.Add(xmlSchemaImporter.ImportSchemaType(schemaType.QualifiedName)); } foreach (XmlSchemaElement schemaElement in rootSchema.Elements.Values) { xmlTypeMappings.Add(xmlSchemaImporter.ImportTypeMapping(schemaElement.QualifiedName)); } xmlTypeMappings.ForEach(xmlCodeExporter.ExportTypeMapping); CodeGenerator.ValidateIdentifiers(codeNamespace); foreach (CodeTypeDeclaration codeTypeDeclaration in codeNamespace.Types) { for (int i = codeTypeDeclaration.CustomAttributes.Count - 1; i >= 0; i--) { CodeAttributeDeclaration cad = codeTypeDeclaration.CustomAttributes[i]; if (cad.Name == "System.CodeDom.Compiler.GeneratedCodeAttribute") { codeTypeDeclaration.CustomAttributes.RemoveAt(i); } } } using (var writer = new StringWriter()) { new CSharpCodeProvider().GenerateCodeFromNamespace(codeNamespace, writer, new CodeGeneratorOptions()); //Console.WriteLine(writer.GetStringBuilder().ToString()); File.WriteAllText(Path.Combine(rootFolder, "FpML4_2.Generated.cs"), writer.GetStringBuilder().ToString()); } Console.ReadLine(); }
public void XsdToClassTest() { // identify the path to the xsd string xsdFileName = "Account.xsd"; string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); string xsdPath = Path.Combine(path, xsdFileName); // load the xsd XmlSchema xsd; using (FileStream stream = new FileStream(xsdPath, FileMode.Open, FileAccess.Read)) { xsd = XmlSchema.Read(stream, null); } Console.WriteLine("xsd.IsCompiled {0}", xsd.IsCompiled); XmlSchemas xsds = new XmlSchemas(); xsds.Add(xsd); xsds.Compile(null, true); XmlSchemaImporter schemaImporter = new XmlSchemaImporter(xsds); // create the codedom CodeNamespace codeNamespace = new CodeNamespace("Generated"); XmlCodeExporter codeExporter = new XmlCodeExporter(codeNamespace); List maps = new List(); foreach (XmlSchemaType schemaType in xsd.SchemaTypes.Values) { maps.Add(schemaImporter.ImportSchemaType(schemaType.QualifiedName)); } foreach (XmlSchemaElement schemaElement in xsd.Elements.Values) { maps.Add(schemaImporter.ImportTypeMapping(schemaElement.QualifiedName)); } foreach (XmlTypeMapping map in maps) { codeExporter.ExportTypeMapping(map); } RemoveAttributes(codeNamespace); // Check for invalid characters in identifiers CodeGenerator.ValidateIdentifiers(codeNamespace); // output the C# code CSharpCodeProvider codeProvider = new CSharpCodeProvider(); using (StringWriter writer = new StringWriter()) { codeProvider.GenerateCodeFromNamespace(codeNamespace, writer, new CodeGeneratorOptions()); Console.WriteLine(writer.GetStringBuilder().ToString()); } Console.ReadLine(); }
static void MapTypes(XmlSchema schema, XmlSchemaImporter importer, CodeNamespace cns, CodeCompileUnit ccu, CodeDomProvider codeProvider, CodeGenerationOptions options, Hashtable mappings) { XmlCodeExporter exporter = new XmlCodeExporter(cns, ccu, codeProvider, options, mappings); foreach (XmlSchemaElement element in schema.Elements.Values) { XmlTypeMapping mapping = importer.ImportTypeMapping(element.QualifiedName); exporter.ExportTypeMapping(mapping); } }
public void Start(string sDirIn, string sDirCppXmlOut, string sDirCppBinOut, string sDirJsBinOut, ValidationEventHandler oValidationEventHandler) { string sXsdPath = sDirIn + "xlsx-ext/" + gc_sXsd; XmlSchemaSet schemaSet = new XmlSchemaSet(); schemaSet.ValidationEventHandler += oValidationEventHandler; schemaSet.Add(null, sXsdPath); schemaSet.Compile(); XmlSchema chartSchema = null; XmlSchemas schemas = new XmlSchemas(); foreach (XmlSchema schema in schemaSet.Schemas()) { if (schema.TargetNamespace == gc_sTargetNamespace) { chartSchema = schema; schemas.Add(schema); } } if (null != chartSchema) { CodeNamespace ns = new CodeNamespace(); XmlCodeExporter exporter = new XmlCodeExporter(ns); CodeGenerationOptions generationOptions = CodeGenerationOptions.GenerateProperties; XmlSchemaImporter importer = new XmlSchemaImporter(schemas, generationOptions, new ImportContext(new CodeIdentifiers(), false)); foreach (XmlSchemaElement element in chartSchema.Elements.Values) { XmlTypeMapping mapping = importer.ImportTypeMapping(element.QualifiedName); exporter.ExportTypeMapping(mapping); } CodeGenerator.ValidateIdentifiers(ns); ////Microsoft.CSharp.CSharpCodeProvider oProvider; //// output the C# code //Microsoft.CSharp.CSharpCodeProvider codeProvider = new Microsoft.CSharp.CSharpCodeProvider(); //using (StringWriter writer = new StringWriter()) //{ // codeProvider.GenerateCodeFromNamespace(ns, writer, new CodeGeneratorOptions()); // string sCode = writer.GetStringBuilder().ToString(); //} List <GenClassPivot> aGenClasses = PreProcess(ns, chartSchema); aGenClasses = FilterClassesSlicer(aGenClasses); (new CodegenSlicerCPP()).Process(sDirCppXmlOut, aGenClasses, gc_sTargetNamespace); //(new CodegenJS()).Process(sDirJsBinOut, aGenClasses); } }
private static void UpdateGeneratedCodeAttribute(XmlCodeExporter exporter, string version) { var property = exporter.GetType().GetProperty("GeneratedCodeAttribute", BindingFlags.Instance | BindingFlags.NonPublic); var attribute = property.GetValue(exporter, null) as CodeAttributeDeclaration; if (attribute == null) { return; } attribute.Arguments[0].Value = new CodePrimitiveExpression("xsd"); attribute.Arguments[1].Value = new CodePrimitiveExpression(version); }
public static void GenerateCode(string xsdFilepath, string codeOutPath, string nameSpace) { FileStream stream = File.OpenRead(xsdFilepath); XmlSchema xsd = XmlSchema.Read(stream, ValidationCallbackOne); // Remove namespaceattribute from schema xsd.TargetNamespace = null; XmlSchemas xsds = new XmlSchemas { xsd }; XmlSchemaImporter imp = new XmlSchemaImporter(xsds); //imp.Extensions.Add(new CustomSchemaImporterExtension()); CodeNamespace ns = new CodeNamespace(nameSpace); XmlCodeExporter exp = new XmlCodeExporter(ns); foreach (XmlSchemaObject item in xsd.Items) { if (!(item is XmlSchemaElement)) { continue; } XmlSchemaElement xmlSchemaElement = (XmlSchemaElement)item; XmlQualifiedName xmlQualifiedName = new XmlQualifiedName(xmlSchemaElement.Name, xsd.TargetNamespace); XmlTypeMapping map = imp.ImportTypeMapping(xmlQualifiedName); exp.ExportTypeMapping(map); } // Remove all the attributes from each type in the CodeNamespace, except // System.Xml.Serialization.XmlTypeAttribute RemoveAttributes(ns); ToProperties(ns); CodeCompileUnit compileUnit = new CodeCompileUnit(); compileUnit.Namespaces.Add(ns); CSharpCodeProvider provider = new CSharpCodeProvider(); using (StreamWriter sw = new StreamWriter(codeOutPath, false)) { CodeGeneratorOptions codeGeneratorOptions = new CodeGeneratorOptions(); provider.GenerateCodeFromCompileUnit(compileUnit, sw, codeGeneratorOptions); } }
static void Main(string[] args) { var xmlSchemas = new XmlSchemas(); xmlSchemas.Add(XmlSchema.Read(File.OpenRead("contacts.xsd"), validationHandler)); xmlSchemas.Compile(validationHandler, true); XmlSchemaImporter schemaImporter = new XmlSchemaImporter(xmlSchemas); CodeNamespace codeNamespace = new CodeNamespace("CSharpGenerated"); XmlCodeExporter codeExporter = new XmlCodeExporter(codeNamespace, null, CodeGenerationOptions.None); foreach (XmlSchema xsd in xmlSchemas) { foreach (XmlSchemaElement schemaElement in xsd.Elements.Values) { Console.WriteLine($"{schemaElement.Name} is {schemaElement.GetType().Name}"); var t = schemaImporter.ImportTypeMapping(schemaElement.QualifiedName); codeExporter.ExportTypeMapping(t); } foreach (XmlSchemaType schemaType in xsd.SchemaTypes.Values) // XmlSchemaComplexType or XmlSchemaSimpleType { var t = schemaImporter.ImportSchemaType(schemaType.QualifiedName); Console.WriteLine($"{schemaType.Name} is a {schemaType.GetType().Name}"); // Generates far to many xmlroot attributes //codeExporter.ExportTypeMapping(schemaImporter.ImportSchemaType(schemaType.QualifiedName)); } } RemoveAttributes(codeNamespace); CodeGenerator.ValidateIdentifiers(codeNamespace); CSharpCodeProvider codeProvider = new CSharpCodeProvider(); CodeGeneratorOptions opts = new CodeGeneratorOptions { BlankLinesBetweenMembers = false, VerbatimOrder = true }; codeProvider.GenerateCodeFromNamespace(codeNamespace, Console.Out, opts); foreach (CodeTypeDeclaration codeType in codeNamespace.Types) { Console.WriteLine($"{codeType.Name} is a {codeType.GetType().Name}"); var t = codeType.TypeParameters; } Console.ReadLine(); }
static void Main(string[] args) { // identify the path to the xsd const string xsdFileName = @"schema.xsd"; var path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); var xsdPath = Path.Combine(path, xsdFileName); // load the xsd XmlSchema xsd; using (var stream = new FileStream(xsdPath, FileMode.Open, FileAccess.Read)) { xsd = XmlSchema.Read(stream, null); } var xsds = new XmlSchemas(); xsds.Add(xsd); xsds.Compile(null, true); var schemaImporter = new XmlSchemaImporter(xsds); // create the codedom var codeNamespace = new CodeNamespace("Generated"); var codeExporter = new XmlCodeExporter(codeNamespace); var maps = new List <XmlTypeMapping>(); foreach (XmlSchemaType schemaType in xsd.SchemaTypes.Values) { maps.Add(schemaImporter.ImportSchemaType(schemaType.QualifiedName)); } foreach (XmlSchemaElement schemaElement in xsd.Elements.Values) { maps.Add(schemaImporter.ImportTypeMapping(schemaElement.QualifiedName)); } foreach (var map in maps) { codeExporter.ExportTypeMapping(map); } PostProcess(codeNamespace); // Check for invalid characters in identifiers CodeGenerator.ValidateIdentifiers(codeNamespace); // output the C# code var codeProvider = new CSharpCodeProvider(); using (var writer = new StringWriter()) { codeProvider.GenerateCodeFromNamespace(codeNamespace, writer, new CodeGeneratorOptions()); Console.WriteLine(writer.GetStringBuilder().ToString()); } }
private CodeNamespace ExportCode() { XmlSchema xsd; XmlSchemas schemas; LoadSchemas(out xsd, out schemas); CodeNamespace ns = new CodeNamespace(base.FileNameSpace); XmlSchemaImporter importer = new XmlSchemaImporter(schemas); XmlCodeExporter exporter = new XmlCodeExporter(ns); GenerateForElements(xsd, importer, exporter); GenerateForComplexTypes(xsd, importer, exporter); return(ns); }
private static CodeNamespace CreateCodeNamespaceFromXsds(string[] xsdFiles, string targetNamespace) { XmlSchemaSet schemas = new XmlSchemaSet(); List <XmlQualifiedName> xmlTypes = new List <XmlQualifiedName>(); // Load the XmlSchema and its collection. foreach (string xsdFile in xsdFiles) { using (FileStream fs = new FileStream(xsdFile, FileMode.Open)) { XmlSchema xsd; xsd = XmlSchema.Read(fs, null); schemas.Add(xsd); foreach (XmlSchemaElement element in xsd.Elements.Values) { if (!xmlTypes.Contains(element.QualifiedName)) { xmlTypes.Add(element.QualifiedName); } } } } schemas.Compile(); // Create the importer for these schemas. XmlSchemaImporter importer = new XmlSchemaImporter(MoveSchemaSetToXmlSchemas(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 (XmlQualifiedName xmlType in xmlTypes) { // Import the mapping first. XmlTypeMapping mapping = importer.ImportTypeMapping(xmlType); // Export the code finally. exporter.ExportTypeMapping(mapping); } RemoveAttributes(ns); return(ns); }
private CodeCompileUnit GenerateTypesWithXmlSchemaImporter(XmlSchemaSet schemas) { CodeNamespace ns = new CodeNamespace(this.targetNamespace); CodeCompileUnit unit = new CodeCompileUnit(); unit.Namespaces.Add(ns); schemas.ValidationEventHandler += this.validationEventHandler; try { // Validate schemas schemas.Compile(); XmlSchemas xsds = new XmlSchemas(); foreach (XmlSchema xsd in schemas.Schemas()) { xsds.Add(xsd); } foreach (XmlSchema schema in xsds) { XmlSchemaImporter importer = new XmlSchemaImporter(xsds); XmlCodeExporter exporter = new XmlCodeExporter(ns, unit); // export only elements foreach (XmlSchemaElement schemaElement in schema.Elements.Values) { exporter.ExportTypeMapping(importer.ImportTypeMapping(schemaElement.QualifiedName)); } CodeGenerator.ValidateIdentifiers(ns); } } catch (ArgumentException argumentException) { throw new InvalidOperationException(argumentException.Message, argumentException.InnerException); } finally { schemas.ValidationEventHandler -= this.validationEventHandler; } return(unit); }
/// <summary> /// Generate code for all of the complex types in the schema /// </summary> /// <param name="xsd"></param> /// <param name="importer"></param> /// <param name="exporter"></param> private void GenerateForComplexTypes( XmlSchema xsd, XmlSchemaImporter importer, XmlCodeExporter exporter) { foreach (XmlSchemaObject type in xsd.SchemaTypes.Values) { XmlSchemaComplexType ct = type as XmlSchemaComplexType; if (ct != null) { Trace.TraceInformation("Generating for Complex Type: {0}", ct.Name); XmlTypeMapping mapping = importer.ImportSchemaType(ct.QualifiedName); exporter.ExportTypeMapping(mapping); } } }
private CodeNamespace GeneratedClassFromStream(Stream stream, string nameSpace) { try { XmlSchema xsd; stream.Seek(0, SeekOrigin.Begin); using (stream) { xsd = XmlSchema.Read(stream, null); } var xsds = new XmlSchemas(); xsds.Add(xsd); xsds.Compile(null, true); var schemaImporter = new XmlSchemaImporter(xsds); // create the codedom var codeNamespace = new CodeNamespace(nameSpace); var codeExporter = new XmlCodeExporter(codeNamespace); var maps = new List <XmlTypeMapping>(); foreach (XmlSchemaType schemaType in xsd.SchemaTypes.Values) { maps.Add(schemaImporter.ImportSchemaType(schemaType.QualifiedName)); } foreach (XmlSchemaElement schemaElement in xsd.Elements.Values) { maps.Add(schemaImporter.ImportTypeMapping(schemaElement.QualifiedName)); } foreach (XmlTypeMapping map in maps) { codeExporter.ExportTypeMapping(map); } return(codeNamespace); } catch (Exception e) { return(null); } }
public void XsdToClassTest(IEnumerable <Func <TextReader> > xsds, TextWriter codeWriter) { var schemas = new XmlSchemas(); foreach (var getReader in xsds) { using (var reader = getReader()) { var xsd = XmlSchema.Read(reader, null); schemas.Add(xsd); } } schemas.Compile(null, true); var schemaImporter = new XmlSchemaImporter(schemas); var maps = new List <XmlTypeMapping>(); foreach (XmlSchema xsd in schemas) { foreach (XmlSchemaType schemaType in xsd.SchemaTypes.Values) { maps.Add(schemaImporter.ImportSchemaType(schemaType.QualifiedName)); } foreach (XmlSchemaElement schemaElement in xsd.Elements.Values) { maps.Add(schemaImporter.ImportTypeMapping(schemaElement.QualifiedName)); } } // create the codedom var codeNamespace = new CodeNamespace(this.Namespace); var codeExporter = new XmlCodeExporter(codeNamespace); foreach (XmlTypeMapping map in maps) { codeExporter.ExportTypeMapping(map); } ModifyGeneratedCode(codeNamespace); // Check for invalid characters in identifiers CodeGenerator.ValidateIdentifiers(codeNamespace); // output the C# code var codeProvider = new CSharpCodeProvider(); codeProvider.GenerateCodeFromNamespace(codeNamespace, codeWriter, new CodeGeneratorOptions()); }
/// <summary> /// Generates the data objects with code DOM. /// </summary> /// <param name="targetFolder">The target folder.</param> /// <param name="targetXmlFile">The target XML file specifying the list of top-level schemas to process.</param> /// <param name="nameSpace">The name space.</param> /// <param name="dataSchemaRootFolder">The root folder for the data schemas.</param> /// <param name="standardFamily">The standard family.</param> /// <param name="dataSchemaVersion">The data schema version.</param> /// <param name="dataObjects">The data objects.</param> /// <param name="schemaSubstitutions">The schema substitutions. The keys are top-level schemas. The values are included schemas that the top-level schemas are to be substituted for.</param> public static void GenerateDataObjectsWithCodeDom(string targetFolder, string targetXmlFile, string nameSpace, string dataSchemaRootFolder, string standardFamily, string dataSchemaVersion, List <string> dataObjects, Dictionary <string, string> schemaSubstitutions, Dictionary <string, string> namespaceSubstitutions) { var schemas = LoadAndCompileAllSchemas(targetXmlFile, dataSchemaRootFolder, schemaSubstitutions, namespaceSubstitutions); var codeProvider = CodeDomProvider.CreateProvider("CS"); var codeNamespace = new CodeNamespace(nameSpace); var codeCompileUnit = new CodeCompileUnit(); var outputFile = Path.Combine(targetFolder, "DataObject.cs"); var options = CodeGenerationOptions.GenerateProperties; var version = "2.0.50727.3038"; var importer = new XmlSchemaImporter(schemas, options, codeProvider, new ImportContext(new CodeIdentifiers(), false)); var exporter = new XmlCodeExporter(codeNamespace, codeCompileUnit, codeProvider, options, null); codeNamespace.Imports.Add(new CodeNamespaceImport(typeof(XmlRootAttribute).Namespace)); codeCompileUnit.Namespaces.Add(codeNamespace); AddNamespaceComments(codeNamespace, version); UpdateGeneratedCodeAttribute(exporter, version); foreach (XmlSchema schema in schemas) { ImportXmlSchema(schema, importer, exporter); } foreach (CodeTypeDeclaration typeDeclaration in codeNamespace.Types) { if (typeDeclaration.IsEnum && Has <XmlRootAttribute>(typeDeclaration)) { typeDeclaration.CustomAttributes.Remove(Get <XmlRootAttribute>(typeDeclaration)); } } AddValidationAttributes(codeNamespace, schemas.ToList(), standardFamily, dataSchemaVersion, dataObjects); using (var writer = new StreamWriter(outputFile, false, Encoding.UTF8)) { codeProvider.GenerateCodeFromCompileUnit(codeCompileUnit, writer, null); } SchemaGatherer.CleanUpGeneratedCode(outputFile); }
/// <summary> /// Generate code for the elements in the Schema /// </summary> /// <param name="xsd"></param> /// <param name="importer"></param> /// <param name="exporter"></param> private void GenerateForElements( XmlSchema xsd, XmlSchemaImporter importer, XmlCodeExporter exporter) { foreach (XmlSchemaElement element in xsd.Elements.Values) { Trace.TraceInformation("Generating for element: {0}", element.Name); try { XmlTypeMapping mapping = importer.ImportTypeMapping(element.QualifiedName); exporter.ExportTypeMapping(mapping); } catch (Exception ex) { Trace.TraceEvent(TraceEventType.Error, 10, ex.ToString()); } } }
public static void BuildElementName2TargetNamespaceMapping(ICodeGeneratorContext codeGeneratorContext) { XmlSchemas xmlSchemas = codeGeneratorContext.XmlSchemas; CodeNamespace codeNamespace = new CodeNamespace(); const CodeGenerationOptions generationOptions = CodeGenerationOptions.GenerateProperties; var exporter = new XmlCodeExporter(codeNamespace); var importer = new XmlSchemaImporter(xmlSchemas, generationOptions, new ImportContext(new CodeIdentifiers(), false)); IDictionary <string, string> elementName2TargetNamespaceMapping = codeGeneratorContext.ElementName2TargetNamespaceMapping; foreach (XmlSchema schema in xmlSchemas) { foreach (XmlSchemaElement element in schema.Elements.Values) { XmlTypeMapping typeMapping = importer.ImportTypeMapping(element.QualifiedName); elementName2TargetNamespaceMapping[element.QualifiedName.Name] = schema.TargetNamespace; } } }
private static CodeNamespace ProcessSchema(SchemaDefinition schemaDefinition, bool includeDataContractAttributes) { var ns = new CodeNamespace(schemaDefinition.Namespace); var reader = XmlReader.Create(schemaDefinition.SchemaPath); var xsd = XmlSchema.Read(reader, Validate); var schemas = new XmlSchemas(); var schemaSet = new XmlSchemaSet(); schemaSet.Add(xsd); schemaSet.Compile(); foreach (XmlSchema schema in schemaSet.Schemas()) { schemas.Add(schema); } const CodeGenerationOptions generationOptions = CodeGenerationOptions.GenerateOrder; var exporter = new XmlCodeExporter(ns); var importer = new XmlSchemaImporter(schemas, generationOptions, new ImportContext(new CodeIdentifiers(), false)); foreach (var mapping in xsd.Items.OfType <XmlSchemaType>().Select(item => importer.ImportSchemaType(item.QualifiedName))) { exporter.ExportTypeMapping(mapping); } var includes = Helper.GetSchemaIncludes(schemaSet); FilterIncludedTypes(ns, xsd); AddIncludeImports(ns, includes); RemoveXmlRootAttributeForNoneRootTypes(ns, schemaSet); if (includeDataContractAttributes) { AddDataContractAttributes(ns, schemaDefinition.XmlNamespace); } return(ns); }
internal static CodeNamespaceResult CreateCodeNamespace(PhysicalSchema schema, string targetNamespace) { XmlSchemaSet xset = new XmlSchemaSet(); foreach (var file in schema.Files) { var sr = new StringReader(file.Content); xset.Add(XmlSchema.Read(sr, null)); } xset.Compile(); XmlSchemas schemas = new XmlSchemas(); foreach (XmlSchema xmlSchema in xset.Schemas()) { schemas.Add(xmlSchema); } XmlSchemaImporter importer = new XmlSchemaImporter(schemas); var ns = new CodeNamespace(targetNamespace); var exporter = new XmlCodeExporter(ns); var result = new CodeNamespaceResult(); foreach (XmlSchemaElement element in xset.GlobalElements.Values) { XmlTypeMapping mapping = importer.ImportTypeMapping(element.QualifiedName); if (string.IsNullOrEmpty(result.RootElementName)) { result.RootElementName = mapping.TypeName; } exporter.ExportTypeMapping(mapping); } result.Code = ns; return(result); }
private CodeCompileUnit ExportCodeFromSchemas(XmlSchemas schemas) { CodeNamespace ns = new CodeNamespace(this.TargetNamespace); CodeCompileUnit unit = new CodeCompileUnit(); unit.Namespaces.Add(ns); XmlSchemaImporter importer = new XmlSchemaImporter(schemas, CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync, new ImportContext(new CodeIdentifiers(), true)); XmlCodeExporter exporter = new XmlCodeExporter(ns, unit, CodeGenerationOptions.GenerateNewAsync | CodeGenerationOptions.GenerateProperties); List <XmlTypeMapping> mappings = new List <XmlTypeMapping>(); foreach (XmlSchema xsd in schemas) { foreach (XmlSchemaType type in xsd.SchemaTypes.Values) { mappings.Add(importer.ImportSchemaType(type.QualifiedName)); } if (!this.ProcessComplexTypesOnly) { foreach (XmlSchemaElement element in xsd.Elements.Values) { mappings.Add(importer.ImportTypeMapping(element.QualifiedName)); } } } foreach (XmlTypeMapping mapping in mappings) { exporter.ExportTypeMapping(mapping); } CodeGenerator.ValidateIdentifiers(ns); return(unit); }
} //method GenerateSchemaForDocument private CodeNamespace GenerateCodeForSchema(XmlSchema schema) { XmlSchemas schemas = new XmlSchemas(); schemas.Add(schema); XmlSchemaImporter imp = new XmlSchemaImporter(schemas); CodeNamespace tempSpace = new CodeNamespace(); XmlCodeExporter exp = new XmlCodeExporter(tempSpace); // Iterate schema items (top-level elements only) and generate code for each foreach (XmlSchemaObject item in schema.Items) { if (item is XmlSchemaElement) { // Import the mapping first XmlTypeMapping map = imp.ImportTypeMapping(new XmlQualifiedName(((XmlSchemaElement)item).Name, schema.TargetNamespace)); // Export the code finally exp.ExportTypeMapping(map); } //if } //foreach return(tempSpace); } //method GenerateCodeForSchema
public static CodeNamespace Process(string xsdSchema, string modelsNamespace) { // Load the XmlSchema and its collection. XmlSchema xsd; using (var fs = new StringReader(xsdSchema)) { 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(modelsNamespace); 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); } // execute extensions //var collectionsExt = new ArraysToCollectionsExtension(); //collectionsExt.Process(ns, xsd); //var filedsExt = new FieldsToPropertiesExtension(); //filedsExt.Process(ns, xsd); return(ns); }
private static void GenerateClasses(CodeNamespace code, XmlSchema schema) { XmlSchemas schemas = new XmlSchemas(); schemas.Add(schema); XmlSchemaImporter importer = new XmlSchemaImporter(schemas); CodeCompileUnit codeCompileUnit = new CodeCompileUnit(); CodeGenerationOptions options = CodeGenerationOptions.None; XmlCodeExporter exporter = new XmlCodeExporter(code, codeCompileUnit, options); foreach (XmlSchemaObject item in schema.Items) { XmlSchemaElement element = item as XmlSchemaElement; if (element != null) { XmlQualifiedName name = new XmlQualifiedName(element.Name, schema.TargetNamespace); XmlTypeMapping map = importer.ImportTypeMapping(name); exporter.ExportTypeMapping(map); } } }
private static void AddTypes(CodeNamespace codeNamespace, XmlSchemaSet schemaSet) { var schemas = new XmlSchemas(); foreach (var schema in schemaSet.Schemas().Cast <XmlSchema>()) { schemas.Add(schema); } var schemaImporter = new XmlSchemaImporter(schemas); #if NETFRAMEWORK schemaImporter.Extensions.Add(new NodaTimeSchemaImporterExtension()); var codeExporter = new XmlCodeExporter(codeNamespace); foreach (var schemaObject in schemas.SelectMany(e => e.Items.Cast <XmlSchemaObject>())) { XmlTypeMapping mapping; switch (schemaObject) { case XmlSchemaType schemaType: mapping = schemaImporter.ImportSchemaType(schemaType.QualifiedName); break; case XmlSchemaElement schemaElement: mapping = schemaImporter.ImportTypeMapping(schemaElement.QualifiedName); break; default: continue; } codeExporter.ExportTypeMapping(mapping); } CodeGenerator.ValidateIdentifiers(codeNamespace); #else throw new PlatformNotSupportedException($"{nameof(XmlCodeExporterAssemblyCreator)} is not available"); #endif }