Dynamically Map a DataSet to StringTemplate
I am using StringTemplate in a Windows Service notification project (.NET 4.0). My objective is to read in and process XML files that define a query and a stringtemplate. The class then binds the results from a DataTable into the template for emailing. Below is an XML snippet and the LINQ statement and the C# to do the binding.
<!-- XML Data Original-->
<Items>
<Item>
<Query>
Select name, title, date from People;
</Query>
<Template>
Welcome $name to $title$ on $date$.
</Template>
</Item>
</Items>
var dataTable = data开发者_C百科base.GetQuery(query);
var data = (from dataRow in dataTable.AsEnumerable()
select new
{
Name = dataRow.Field<string>("Name"),
Title = dataRow.Field<string>("Title"),
Date = dataRow.Field<DateTime>("Date")
}).Distinct();
stringTemplate.SetAttribute("Name", data.Name);
stringTemplate.SetAttribute("Title", data.Title);
stringTemplate.SetAttribute("Date", data.Date);
The problem is the above C# is static, I would like to make it dynamic. That is what if I need to add another field in the XML query element and a corresponding template field?
<!-- XML Data Modified-->
<Items>
<Item>
<Query>
Select name, title, date, location from People;
</Query>
<Template>
Welcome $name to $title$ on $date$ at $location$.
</Template>
</Item>
</Items>
The DataTable contains the new column, however my LINQ statement and binding code does not. My question is what strategy could I employ to fetch and bind the data from the DataTable to my stringtemplate dynamically? Note I am currently using LINQ but the solution does not have to.
The approach I took is not projecting into an anonymous type and in the String Template file iterating over the collection. I also treat a single record "static" in the same manner but I use a FirstOrDefault filter on the Linq statement.
C#:
var dataTable = database.GetQuery(query);
var data = (from dataRow in dataTable.AsEnumerable()
select dataRow);
stringTemplate.SetAttribute("dynamic", data);
Template:
$dynamic:{ d |
Welcome $d.name$ to $d.title$ on $d.date$ at $d.location$
}$
精彩评论