views:

72

answers:

2

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), then 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

A: 

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

Gurdas Nijor
A: 

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>
    }
}
Darin Dimitrov
That's exactly it - thanks Darin!
MarkB