T4 Template Using XML


In this article we learn what a Text Template Transformation Toolkit (T4) template is using XML. If you are unfamiliar with the T4 template then please read my article What a T4 Template is in MVC.

Let’s create an empty MVC4 project.

Go to File → Project.

Select ASP.NET MVC 4 Web Application and name it T4TemplateUsingXml.

mvc web application

Click Ok.

Select an Empty Project.


After creating the project let’s add a folder called Xml in the root directory.

ADD new Folder

Right-click on the Xml folder and add a XML file and name it Employee.xml.

ADD XML file

After creating Employee.xml paste in the following code.



<Name>Ravi Kant</Name>




To create a model right-click on the Models folder and add a class and name it Employee and paste in the following code:

using System;
using System.Xml.Serialization;
namespace T4TemplateUsingXml.Models
[XmlRoot("Employee"), XmlType("Employee")]
public class Employee
public string Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }

Now we create a controller, right-click on the Controller folder and add a controller named HomeController.

Home Controller

And then right-click on the index code inline and choose Add View using a scaffold empty template.

Add View

Add View1

Let’s run the project and see the output.


Now I make a copy of List.tt and name it PramodList.tt and make some changes. After that add another view called IndexXml using a scaffold PramodList template.

//Location of List.tt is C:\Program Files\Microsoft Visual Studio 11.0\Common7\IDE\ItemTemplates\CSharp\Web\MVC 4\CodeTemplates\AddView\CSHTML

Add View List

And write some code in HomeController as in the following:

public ActionResult IndexXml()
string Data = Server.MapPath("~/Xml/Employee.xml");
DataSet ds = new DataSet();
var employee = new List<Employee>();
employee = (from item in ds.Tables[0].AsEnumerable()
select new Employee
Id = item[0].ToString(),
Name = item[1].ToString(),
Email = item[2].ToString(),
return View(employee);

And run the application.

Index XML

Note: I am attaching a PramodList.tt along with the application. Please paste the PramodList.tt file into the following folder:

C:\Program Files\Microsoft Visual Studio 11.0\Common7\IDE\ItemTemplates\CSharp\Web\MVC 4\CodeTemplates\AddView\CSHTML

In the application I am just attaching Controller, Models, Views and XML folders.

I hope you enjoy this article.

Happy coding 🙂

Tags: ,