Search This Blog

Monday, January 30, 2006

How do I produce well-formed XML with Velocity?

The title pretty much says it all. I’ve been reading the docs, googling around and asking the only person I know who actually likes Velocity, but I could not find a solution to this simple question: Is it possible to guarantee that the output of a Velocity template will always be a well-formed XML document?

Of course, the template must have all tags balanced and such, to start with. Consider this simple template:

$value

As long as the string representation of the value variable in the Velocity context is something innocuous as “foobar”, everything is fine. But if it were “foo & bar” instead, you’d get this output:
foo & bar

which is most definitely not valid XML! The correct output should have been:


foo & bar

This makes me wonder: Do people who use Velocity to generate Web pages never need to generate valid XHTML pages? I simply can’t believe this!

So there must be a solution. Of course, there is a really obvious and bad solution, which is going over all the values passed into the Velocity context and escaping all XML special characters like ‘&’, ‘<’ and so on. This might work for a simple case like the one above, but would break down horribly when your data model is a complex collection of arbitrary objects.

Please, don’t tell me that Velocity sucks as much as I think it does!

No comments: