您可以使用模板引擎來實現此目的。第一步是定義包含對象屬性值的佔位符的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