Craftsman at Work

I'm Artur Karbone, coding software architect and independent IT consultant and this is my blog about craftsmanship, architecture, distributed systems, management and much more.

Leveraging T4 Templates

T4 (which stands for Text Template Transformation Toolkit) is a great way to automate code generation tasks. Here is a sample of how I translated resx file (which is kind of key/value xml) into JSON:

<#@ template debug="false" hostspecific="false" language="C#" #>  
<#@ assembly name="System.Core" #>  
<#@ assembly name="System.Xml" #>  
<#@ assembly name="System.Xml.Linq" #>  
<#@ import namespace="System.Linq" #>  
<#@ import namespace="System.Text" #>  
<#@ import namespace="System.Xml.Linq" #>  
<#@ import namespace="System" #>  
<#@ import namespace="System.Collections.Generic" #>  
<#@ output extension=".txt" #>  
{
<#  
XDocument resourceXML = XDocument.Load(@"C:\translations-en.resx");

var translations =  
        from tr in resourceXML.Descendants("data")
        select new Tuple<string,string>(tr.Attribute("name").Value, tr.Element("value").Value);                    

 foreach(Tuple<string,string> translation in translations)
 {#>
    "<#=translation.Item1#>" : "<#=translation.Item2#>",
<#}#>  
}
comments powered by Disqus