开发者

Binding a POCO to an html document and generating the result to a string

I am trying to return an html string from a method in a class library (don't ask why). What i would like to do within the method is get an instance of a POCO from my domain, then open an html document (maybe from a file or maybe it is a string from somewhere else), the开发者_如何学JAVAn pass the POCO to the document (which has bindings to the POCOs properties), then output the resulting html.

Is there a nice wrapper to get this done in the .NET framework? I saw this article on the HtmlDocument class, but was hoping to avoid all the direct element access and assignments:

http://msdn.microsoft.com/en-us/library/system.windows.forms.htmldocument.aspx


You could use a templating engine to achieve this. The first step would be to define your HTML template containing placeholders for the object property values. Then you feed the templating engine with the template and an object which will produce the final result. Here's an example using 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>
    }
}


My overall approach would be to use an appropriate XML Serializer (DataContractSerializer or the XmlSerializer,) pass your serializable POCO in, recieve the resulting XML; and transform that with an XSLT stylesheet to generate the output HTML.

The transformation pipeline would look something like this

POCO    ----[XmlSerializer]-->    XML    -------[XSLT]----->   HTML

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜