Archive | NVelocity RSS feed for this section

NVelocity XML encode all string variables

1 Nov

Getting started with NVelocity:

The library (choose either or; my preference is the Castle project one):

The basic setup code for NVelocity:

var outputBuffer = new StringBuilder();


var velocityContext = new VelocityContext();

var model = new Model();

velocityContext.Put(“model”, model);

var template = Velocity.GetTemplate(“Template.vm”);

template.Merge(velocityContext, new StringWriter(outputBuffer));

The model:

public class Model


public String MyVariable


get { return “Test & Encode”; }



The template (Template.vm; mark file as copy to Output directory):

<?xml version=”1.0″ encoding=”UTF-8″?>




XML encoding:

The subscription to add a behavior over NVelocity parsing:

velocityContext.EventCartridge.ReferenceInsertion += EventCartridge_ReferenceInsertion_XmlEscapingAllStringContent; // add our custom handler to the ReferenceInsertion event

The behavior to XML escape:

private static void EventCartridge_ReferenceInsertion_XmlEscapingAllStringContent(object sender, ReferenceInsertionEventArgs e)

var originalString = e.OriginalValue as string;

if (originalString == null)

e.NewValue = SecurityElement.Escape(originalString);


Expected Output:

<?xml version=”1.0″ encoding=”UTF-8″?>


Test & Encode



I am using this to generate a 760mb file which takes a few seconds to generate. It seems NVelocity is a good solution for generating files, as it keeps models clean and gives an ASP.NET MVC feel to file creation where the view (in the case an NVelocity template) has the output logic, pulling information from models.