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:

<tag>$value</tag>

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:

<tag>foo & bar</tag>

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

<tag>foo &amp; bar</tag>

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!

4 Responses to “How do I produce well-formed XML with Velocity?”


  1. 1 Lance Lavandowska

    For Roller (rollerweblogger.org) we passed content through a Java method, say escape(String str) which escaped any such thing.
    <tag>#escape($value))</tag>
    It’s been a couple years, so I may not have the syntax exactly right.
    Yes it’s lame, someone should contribute a real solution to the Velocity Tools project

  2. 2 Stephane Bailliez

    Guys, this is in the documentation here.

  3. 3 ugo

    OK, so there are some solutions, which require some amount of work, but I would expect such a feature to be built in: Just set a flag and have Velocity output well-formed XML.

  4. 4 kkk

    I think that every tool should be used keeping in mind what this tool can really do.. Sure Velocity can be used to produce web content but there are better solutions.
    I use Velocity with Ant to produce configuration file using the Texen task and it’s much better than use only ant filtering capabilities.

Leave a Reply