I still stand with my almost 15 year old XML answer [Wayback/Archive] delphi – Writing XML String with proper formatting? – Stack Overflow
Do not generate XML by hand PERIOD.
Writing correct code for escaping complex data (for instance XML, HTML or other SGML in XML, escaped CDATA) is not worth it.
The escaping you do is just a start. Wait until someone puts something in your data that is incompatible.
Many databases support creating well formed XML from queries anyway (see the other answers), that is a direction you should be looking into.
Transforming input data into well formed XML document (let alone valid XML) is way too complex because XML is a relatively complex language including many features making assembling a well formed XML document harder:





