Dynamically Map a DataSet to StringTemplate

北慕城南 提交于 2020-01-16 19:43:08

问题


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 = database.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.


回答1:


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$
}$


来源:https://stackoverflow.com/questions/5210792/dynamically-map-a-dataset-to-stringtemplate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!