Last active
January 7, 2016 01:23
-
-
Save vendettamit/15a8d1be755069f14b62 to your computer and use it in GitHub Desktop.
T4 Template to generate classes from XML file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<#@ template debug="true" hostSpecific="true" #> | |
<#@ output extension=".cs" #> | |
<#@ Assembly Name="System.Core.dll" #> | |
<#@ Assembly Name="System.Xml.dll" #> | |
<#@ Assembly Name="System.Xml.Linq.dll" #> | |
<#@ Assembly Name="System.Windows.Forms.dll" #> | |
<#@ import namespace="System" #> | |
<#@ import namespace="System.IO" #> | |
<#@ import namespace="System.Diagnostics" #> | |
<#@ import namespace="System.Linq" #> | |
<#@ import namespace="System.Xml.Linq" #> | |
<#@ import namespace="System.Collections" #> | |
<#@ import namespace="System.Collections.Generic" #> | |
<# | |
//template code - you get IntelliSense here | |
var str_fileName = "GlobalActionsElements.xml"; | |
var projDir = System.IO.Path.GetDirectoryName(this.Host.TemplateFile); | |
string str_XMLFileNamePath = Path.Combine(projDir, str_fileName); | |
// Certainly you would normally load the model data from a file using | |
// the relative path of the template as shown below: | |
// string SampleInputFileContent = System.IO.File.ReadAllText( | |
// System.IO.Path.GetDirectoryName(this.Host.TemplateFile) + "\\datafile.xml"); | |
#> | |
// This is the output code from your template | |
// you only get syntax-highlighting here - not intellisense | |
namespace WebTest{ | |
public static class <#= Path.GetFileNameWithoutExtension(str_XMLFileNamePath).Replace(".","") #> | |
{ | |
<# GenerateConstants(str_XMLFileNamePath); #> | |
} | |
} | |
<#+ | |
// Insert any template procedures here | |
void GenerateConstants(string path) | |
{ | |
System.Xml.Linq.XDocument doc = System.Xml.Linq.XDocument.Load(path); | |
var classes = from c in doc.Descendants("uielements") | |
where c.NodeType != System.Xml.XmlNodeType.Comment | |
select c.Descendants(); | |
foreach (var item in classes.ToList()) | |
{ | |
IEnumerable<string> constants = item.Descendants("element").Select(x => x.Attribute("Name").Value); | |
if(constants.Count() == 0) | |
{ | |
constants = item.Select(x => x.Attribute("Name").Value); | |
} | |
foreach (var node in constants) | |
{ | |
#> | |
public const string <#= node.ToUpper() #> = "<#= node #>"; | |
<#+ | |
} | |
} | |
} | |
#> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment