> Use an isolated serializer
Some old reference material (XML isn't as common as JSON anymore), but still worthwhile learning: don't output data formats directly. Directly = echo, print, printf,println...whatever your syntax suggests. I see this happen a lot with my junior engineers, and I have this same conversation with them.
Prefer to use data serializers that encapsulate all the syntactical rules that go along with XML, CSV, JSON, YAML, etc. Let the serializers do the grunt work of writing output in correct format.
Some serializers aren't always ideal - correctness and speed can be an issue. Nonetheless, prefer to use those mechanisms over writing your own output.