[Click here to return to the main page of this project]
Now let's write a more complicated template with arguments and usage of the System.Xml.dll assembly. Suppose you'd like to generate class declarations in C# from a XML configuration file.
<?xml version="1.0" encoding="utf-8" ?>
<classes>
<class name="Customer">
<attribute name="name"/>
<attribute name="age"/>
</class>
<class name="Department">
<attribute name="location"/>
</class>
</classes>
Go to the [download section] to download the complete source code.
Have a look at the template. It uses the System.Xml and System.Collection namespaces and gets two arguments. The first argument is the name of the current class to generate code for, the second one is an arraylist consisting of attribute names:
<%@ Assembly Name="System.Xml" %> <%@ Import NameSpace="System.Xml" %> <%@ Import NameSpace="System.Collections" %> <%@ Argument Name="className" Type="string" %> <%@ Argument Name="attributes" Type="ArrayList" %> class <%=className%> { <% foreach(string attr in attributes) { %> public string <%=attr%>; <% } %> }Go to the [download section] to download the complete source code.
Now, see the driver code. It reads the XML file and calls the template for each class, providing a class and attributes as arguments:
using System; using System.Collections; using System.Xml; using TemplateMaschine; namespace Sample { class SampleDriver2 { static void Main(string[] args) { // Load a template from file 'Sample2.template' and compile it Template myTemplate = new Template("Sample2.template"); // Read file 'Config.xml' ArrayList attributes = new ArrayList(); XmlDocument document = new XmlDocument(); document.Load("Config.xml"); XmlNode root = document["classes"]; foreach (XmlNode classNode in root.ChildNodes) { string className = classNode.Attributes["name"].Value; attributes.Clear(); foreach (XmlNode attributeNode in classNode.ChildNodes) { string attributeName = attributeNode.Attributes["name"].Value; attributes.Add(attributeName); } // process the template with className and attributes arguments // and write output to file '<classname>.cs' myTemplate.Generate(new object[] { className, attributes }, className + ".cs"); } } } }Go to the [download section] to download the complete source code.
After compiling and running the code (e.g. by making corresponding changes to run.bat), the output looks like this:
class Customer { public string name; public string age; }File 'Department.cs':
class Department { public string location; }Go to the [download section] to download the complete source code.
[Click here to return to the main page of this project]