我应该采取哪种方法在C#中的模板? [英] Which approach to templating in C# should I take?
问题描述
我有
口具有被存储在数据库中的模板,和JSON数据被转换成在C#字典
示例:
模板:您好,{名字}
数据:{姓:'杰克'}
这有一个数据级别使用正则表达式来拉出来在模板中{}什么工作很容易。
< 。p>我要什么
我希望能够在JSON比第一层要深究下去
例如:
模板:您好,{名称:{一}}
数据:{名称:{第一:'杰克',最后: 史密斯'}}
什么办法,我应该考虑? (并在那里与你挑启动一些指导)
- 正则表达式
- 不使用JSON在模板(支持XSLT或类似的东西)
- 有些东西
我也可为d想通过在模板中的数据要能循环,但我不知道在所有从哪里开始的那一个!
由于堆
下面是我会怎么做:
您的模板更改为这种格式您好,{Name.First}
现在创建一个的JavaScriptSerializer
到JSON转换成词典<字符串对象>
的JavaScriptSerializer JSS =新的JavaScriptSerializer();
动态D = jss.Deserialize(数据的typeof(对象));
现在变量 D
具有的价值您的JSON在字典中。
有,您可以对一个正则表达式运行模板来替换 {XYZN}
与
:字典,递归
完整的例子的钥匙公共无效测试()
{
//你的模板是简单的
字符串模板=您好,{Name.First};
//一些JSON
字符串数据= @{姓名:{第一:杰克,上:史密斯}};
的JavaScriptSerializer JSS =新的JavaScriptSerializer();
//现在`D`包含字典中的
你需要的所有值,动态D = jss.Deserialize(数据的typeof(对象));
//放送针对正则表达式了
//模板提取需要更换
变种结果= Regex.Replace(模板中,标记@{{( [^}] +)}},(M)=>
{
//跳过码值(例如:{{转义值}})
如果(m.Value .StartsWith({{))
返回m.Value;
//通过`.`拆分令牌对字典
VAR件= m.Groups运行[1] .Value.Split('。');
动态值= D;
//去所有的作品后,里面
递归去//比如: Name.First
//第1步(值=值[名称])
//值=新词典<字符串对象>
// {
// {第一:杰克},{上:史密斯}
//};
//第2步(值=值[第一])
//值=杰克
的foreach(VAR在一块块)
{
值=值[片] //去每次
}
返回值内;
});
}
我没有处理异常(如价值不能找到) ,你可以处理这种情况,并返回匹配的值,如果未找到它。 m.Value
为原始值或 m.Groups [1] .value的
之间为字符串 {}
。
What I have I have templates that are stored in a database, and JSON data that gets converted into a dictionary in C#.
Example:
Template: "Hi {FirstName}"
Data: "{FirstName: 'Jack'}"
This works easily with one level of data by using a regular expression to pull out anything within {} in the template.
What I want I would like to be able to go deeper in the JSON than the first layer.
Example:
Template: "Hi {Name: {First}}"
Data: "{Name: {First: 'Jack', Last: 'Smith'}}"
What approach should I be taking? (and some guidance on where to start with your pick)
- A regular expression
- Not use JSON in the template (in favor of xslt or something similar)
- Something else
I'd also like to be able to loop through data in the template, but I have no idea at all where to start with that one!
Thanks heaps
Here is how I would do it:
Change your template to this format Hi {Name.First}
Now create a JavaScriptSerializer
to convert JSON in Dictionary<string, object>
JavaScriptSerializer jss = new JavaScriptSerializer();
dynamic d = jss.Deserialize(data, typeof(object));
Now the variable d
has the values of your JSON in a dictionary.
Having that you can run your template against a regex to replace {X.Y.Z.N}
with the keys of the dictionary, recursively.
Full Example:
public void Test()
{
// Your template is simpler
string template = "Hi {Name.First}";
// some JSON
string data = @"{""Name"":{""First"":""Jack"",""Last"":""Smith""}}";
JavaScriptSerializer jss = new JavaScriptSerializer();
// now `d` contains all the values you need, in a dictionary
dynamic d = jss.Deserialize(data, typeof(object));
// running your template against a regex to
// extract the tokens that need to be replaced
var result = Regex.Replace(template, @"{?{([^}]+)}?}", (m) =>
{
// Skip escape values (ex: {{escaped value}} )
if (m.Value.StartsWith("{{"))
return m.Value;
// split the token by `.` to run against the dictionary
var pieces = m.Groups[1].Value.Split('.');
dynamic value = d;
// go after all the pieces, recursively going inside
// ex: "Name.First"
// Step 1 (value = value["Name"])
// value = new Dictionary<string, object>
// {
// { "First": "Jack" }, { "Last": "Smith" }
// };
// Step 2 (value = value["First"])
// value = "Jack"
foreach (var piece in pieces)
{
value = value[piece]; // go inside each time
}
return value;
});
}
I didn't handle exceptions (e.g. the value couldn't be found), you can handle this case and return the matched value if it wasn't found. m.Value
for the raw value or m.Groups[1].Value
for the string between {}
.
这篇关于我应该采取哪种方法在C#中的模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!