Generating Files With Razor Engine

By | August 16, 2013

The Razor engine can be used outside of ASP.NET. Beside the cool syntax, it’s a very fast engine! And it’s quite easy to use.
In my example I generate a XML file based on a razor template.
(You have to install the NuGet package “RazorEngine”.

This is my model which I use for the rendering:

public class Person
{
    public int Id { get; set; }
    public string Firstname { get; set; }
    public string Lastname { get; set; }
}

public class ReportModel
{
    public DateTime Date { get; private set; }
    public IList<Person> People { get; private set; }

    public ReportModel()
    {
        this.Date = DateTime.Now;
        this.People = new List<Person>();
    }
}

This is the Razor syntax based template.


	@Model.Date
	@foreach (var person in Model.People)
	{
		
			@person.Firstname
			@person.Lastname
		
	}

And here is the code which parses the Razor template and generates an xml file.

var reportData = new ReportModel();

for (var x = 1; x <= 10000; x++)
{
    reportData.People.Add(new Person() 
            { 
                Id = x, 
                Firstname = "Darko " + x, 
                Lastname = "Micic " + x 
            });
}

using (var writer = new StreamWriter(@"C:\output.xml"))
{
    writer.Write(RazorEngine.Razor.Parse<ReportModel>(
				new StreamReader(@"C:\template.xml").ReadToEnd(), 	
				reportData));
}

Cheers!