When I create an XML document, I use Perl, but this question is language agnostic. Most people seem to do this task with tools like XML::Writer or XML::LibXML. It looks like this:
my $writer = XML::Writer->new();
my $type = "fancy";
$writer->startTag("pants");
$writer->characters($type);
$writer->endTag("pants");
I kind of hate this. It feels like that first web page you create as a beginner web developer where you mix all the HTML, CSS, and PHP code together in the same file because you haven’t learned about MVC yet. And everyone agrees this is terrible and we should separate this all out and try to keep languages separate as much as possible. It improves readability if nothing else.
So why is it ok to put XML in our Perl code? My idea is to use Template::Toolkit just like we do with HTML. So it would look like this:
<pants>
[% type %]
<pants>
Afterwards, I can slurp the result into XML::LibXML and validate the string.
But I don’t think anyone does it this way. Why not? Am I missing something?
I’ve used Template::Toolkit for XML. I’ve also used the more programatic XML::Writer style approach.
If you have a fixed XML structure that you’re simply filling in with data and you have Template::Toolkit already around, then using a TT template for your XML makes a lot of sense; using a template in this case probably makes it a lot easier to properly match the desired schema. But, of course, be careful with properly escaping and encoding everything for XML rather than HTML.
If you’re programatically converting arbitrary structured data to XML then XML::Writer is probably a better choice: if you don’t have a fixed schema then there’s nothing to template.
XML is often used as a portable data serialization format. The archetypal example is starting with some nested HoHoA data structure and converting that to XML through a general serialization interface. The serialization system just has a data structure to walk through so there is no structure to template.
Also, people tend to use the first technique they learn even when there are better ways. I’d guess that most people come across XML for data serialization (rather than structure document storage) first so they keep using serialization techniques even when a template approach would be cleaner.
All of this (even the first paragraph) applies to JSON (and even HTML) equally well.