Click here to Skip to main content
15,894,720 members
Articles / Web Development / ASP.NET

SmartCodeGenerator – Drive Code Generation with XML. Transform XML with ASP.NET instead of XSLT.

Rate me:
Please Sign up or sign in to vote.
2.81/5 (9 votes)
27 Oct 2008CPOL9 min read 56.9K   418   65  
This article describes how we can drive codegeneration with xml. Shows step by step instruction of how to generate strongly typed objects from XSD. ASP.NET developers can also use this paper as reference, who wants to transform xml using ASP.NET instead of XSLT.
using System;
using System.Data;
using System.Configuration;
using System.IO;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.Xml.Schema;
using System.CodeDom;
using System.CodeDom.Compiler;
using Microsoft.CSharp;

namespace SmartCodeGeneratorXsdConsole
{
    class Program
    {
        //
        // SmartCodeGenerator Xsd Console application to generate C# Class from xsd schema.
        //
        // Command line:  <schema>.xsd <filename> 
        // Example: scgxsd_console c:\students.xsd c:\students.cs 
        //

        private static String _xsdpath;
        private static String _filename;

        static void Main(string[] args)
        {
            ParseArgs(args);  
            try
            {
                if (_xsdpath == string.Empty)
                    throw new Exception("Invalid Schema, Cannot find Schema.");
                if (_xsdpath == string.Empty)
                    throw new Exception("Invalid Filename to Generate.");
                Program p = new Program();
                p.Generate();
                
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.ToString()); 
                Console.WriteLine(@"
        // SmartCodeGenerator Xsd Console application to generate C# Class from xsd schema.
        //
        // Command line:  <schema>.xsd <filename>
        // Example:   scgxsd_console c:\students.xsd c:\students.cs 
        //");
    //          
            }
        }

        public void Generate()
        {
            //string xsdFileName = _xsdpath;          
            //string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);          
            //string path = @"C:\DotNetWorkFolder2005\Riccardo\TestProject\AJAXEnabledWebApplication2\AJAXEnabledWebApplication2";
            string xsdPath = _xsdpath;//Path.Combine(path, xsdFileName);          
            // load the xsd file
            XmlSchema xsd;          
            using(FileStream stream = new FileStream(xsdPath, FileMode.Open, FileAccess.Read))          
            {              
                xsd = XmlSchema.Read(stream, null);          
            }          
            Console.WriteLine("xsd.IsCompiled {0}", xsd.IsCompiled);          
            //add xsd to the collection of XmlSchema
            XmlSchemas xsds = new XmlSchemas();          
            xsds.Add(xsd);
            //compile the xsd
            xsds.Compile(null, true);          
            //create instance of XmlSchemaImporter
            XmlSchemaImporter schemaImporter = new XmlSchemaImporter(xsds);          
            // create the codedom          
            CodeNamespace codeNamespace = new CodeNamespace("SmartCodeGen");          
            // crate XmlCodeExpoerter
            XmlCodeExporter codeExporter = new XmlCodeExporter(codeNamespace);          
            
            List<object> maps = new List<object>();          
            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);          
            }          
            // 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());              
                string s = (writer.GetStringBuilder().ToString());
                using (StreamWriter sw = File.CreateText(_filename))
                {
                    sw.Write(s);
                }
            }          
            Console.WriteLine("C# Class Created Successfully.");
              
        }
   
        private static void ParseArgs(String[] args) {
            try {
                if (args.Length >= 1)
                    _xsdpath = args[0];

                if (args.Length >= 2)
                    _filename = args[1];                
            }
            catch {
            }

            if (_xsdpath == null)
                _xsdpath = string.Empty;

            if (_filename == null)
                _filename = string.Empty;
            
        }

        
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
Australia Australia
I have been awarded MVP (Visual C#) for year 2007, 2008, 2009. I am a Microsoft Certified Application Developer (C# .Net). I currently live in Melbourne, Australia. I am a co-founder and core developer of Pageflakes www.pageflakes.com and Founder of Simplexhub, a highly experienced software development company based in Melbourne Australia and Dhaka, Bangladesh. Simplexhub.
My BLOG http://www.geekswithblogs.net/shahed
http://msmvps.com/blogs/shahed/Default.aspx.

Comments and Discussions