Geeks With Blogs
Willem's... {rue if I mellow}

We are *finally* busy updating our CodeXS tool (Online Tool, Source-code Download, Article) to run in the Visual Studio 2005/.NET 2.0 environment.

By default, XSD.EXE now generates properties with standard {get;set;} accessors.  Our tool, while providing the same functionality, also provides a lot more... , so our requirement was to generate the same CodeDOM as it did using VS2003/.NET 1.1. ie. with declared fields, instead of properties.  To get this part to work we have to programmatically emulate the /fields flag used with XSD.EXE. Exactly where and how is the problem. The MSDN documentation hints at using the System.Xml.Serialization.CodeGenerationOptions which is new to .NET 2.0. We finally tracked this down by hacking through the undocumented serialization methods.  The following code example is from the article, now modified to show how it should work for both .NET 2.0 and .NET 1.1:

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);
    XmlSchemas schemas = new XmlSchemas();
    // 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);
#if NET_2_0
    // Create the exporter and generate fields, not properties for .NET 2.0
    XmlCodeExporter exporter = new XmlCodeExporter(ns, new CodeCompileUnit(), 
#else // NET_2_0
    // Create the exporter for .NET 1.1
    XmlCodeExporter exporter = new XmlCodeExporter(ns);
#endif // NET_2_0
    // 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.
    return ns;

Posted on Monday, December 5, 2005 9:33 AM .NET Adventures | Back to top

Comments on this post: CodeXS for VS2005/.NET 2.0 Note # 1

No comments posted yet.
Your comment:
 (will show your gravatar)

Copyright © Willem Fourie | Powered by: