NAVmoble - the pocket-sized ERP
Optimized for Microsoft Dynamics NAV and Windows Mobile powered devices

Monday, July 18, 2005

C# Code Generation with .NET - part 2

   This post is coming to wrap up the classes contained into the System.CodeDom namespace and the code snipsets from my previous post into a simple archtiecture for generating C# classes from Xml content.
Lets have the following class diagram:

Class XmlCodeGenerator provides a public method Generate.
It has the following declaration:

public class XmlCodeGenerator:IXmlCodeGenerator
   public IList Generate(XmlDocument xmlToMap, string targetFolder,string _namespace)

XmlDocument contains the xml content, which should be processed.
targetFolder is the folder, where the source files will be generated.
_namespace is the root namespace for all new classes.
The method returns a list of the class names generated from the xml file.

The core of the code generation is implemented into the XmlNodeToClassMapper
descendant class.
XmlNodeToClassMapper is an abstract class and contains one abstract method:

public abstract class XmlNodeToClassMapper
public abstract System.CodeDom.CodeObject Map(XmlNode nodeToMap,params object[] parameters);

   The XmlCodeGenerator.Generate method iterates over the xml elements and
invokes the Map method of a ClassMapper instance for every xml element,
which have child xml elements or xm attributes. Xml elements without child elements or
xml attributes are mapped to members of the System.String type.

   The VS2003 solution for this sample may be downloaded here.
It contains the XmlCodeGenerator implementation, Unit Tests and sample Windows Application.

   Note that this sample is not meant to be a complete code generation solution. It is intended to illustrate
some of the .NET features, which may be used in code generation scenarios...

No comments: