Over a million developers have joined DZone.

Reading an Xml File in T4 Templates


After I wrote the Generating Code From a File Using T4 Templates post about the use of T4 templates in EF4, I played with them for a while (not in EF but generally with T4 templates). In an old project that I’ve created almost 3 years ago which automated the use of lookup tables I had an enum. That enum was meant to be the connection between an Xml node names and was heavily used in the application. For each Xml node I needed to add an entry in the enum. So I thought what the hell lets see if I could have make it using a T4 template. The result is in the post.

Reading a Xml File in T4 Templates

The first thing to do is to add a new file with the extension of .tt into the project. After I had that T4 template file I started to think what is the way to read an Xml file from the T4. Since the Xml file was a part of the project the use of Path class to get the absolute location was one way to get the file. Pay attention that if you will open the solution from the IDE and not from its location (double click on the solution from its current location) the Path.GetFullPath won’t work. After I had the file it was as simple as to read a Xml using XmlDocument and XPath query. The following example is the T4 I have created:

<#@ template language="C#" #>
<#@ assembly name="System.Core" #>
<#@ assembly name="System.Xml" #>
<#@ import namespace="System.Xml" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.IO" #>
using System;

namespace Examples
public class ExampleClass
#region Enums

public enum eExampleEnum
foreach (string name in this.GetNames())
<#= name #>,

public List<string> GetNames()
List<string> result = new List<string>();
XmlDocument doc = new XmlDocument();
string absolutePath = Path.GetFullPath("File.xml");
foreach (XmlNode node in doc.SelectNodes("/Root/Element"))
return result;


The use of T4 template can help us to generate code using a code generation tool. In the example I showed how you can use a T4 template in order to generate an enum from a given Xml file.



Published at DZone with permission of Gil Fink, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}