您可以使用模板引擎来实现此目的。第一步是定义包含对象属性值的占位符的HTML模板。然后,您使用模板和一个会产生最终结果的对象来提供模板引擎。以下是使用NVelocity的示例:
class Program
{
static void Main(string[] args)
{
Velocity.Init();
// Define a template that will represent your HTML structure.
var template = "<html><body><div>$key1</div><div>$key2.ToString('dd/MM/yyyy')</div></body></html>";
var context = new VelocityContext();
// The values you are passing here could be complex objects with many properties
context.Put("key1", "Hello World");
context.Put("key2", DateTime.Now);
var sb = new StringBuilder();
using (var writer = new StringWriter(sb))
using (var reader = new StringReader(template))
{
Velocity.Evaluate(context, writer, null, reader);
}
Console.WriteLine(sb.ToString());
// This will print: <html><body><div>Hello World</div><div>16/10/2009</div></body></html>
}
}
就是这样 - 感谢达林! – 2009-10-17 01:12:13