I had a similar problem, mucked with XML::Simple, XML::Writer and gave up...
Here's what I did: use HTML::Template to create the XML and then use XML::Tidy to pretty-print it. Works like a charm, and you are in full control of attributes, escaping, and everything else.