[Answer]-Write encoding in xml

1๐Ÿ‘

โœ…

I believe that the latest version of the django rest framework will automatically handle this. When I test it with the following code I can clearly see the header that you desire:

from rest_framework.renderers import XMLRenderer
renderer = XMLRenderer()
print renderer.render('foo')

>>> '<?xml version="1.0" encoding="utf-8"?>\n<root>foo</root>'

If you cannot upgrade your dependency then you can follow the trail below in order to create your own Renderer subclass which will add the correct header. All of the examples from below are for the latest version of the library, so what you find may differ.

The django rest framework uses Renderers to write out the content. These are available in rest_framework/renderers.py. This is the part you want to change:

    xml = SimplerXMLGenerator(stream, self.charset)
    xml.startDocument()
    xml.startElement("root", {})

It happens that it uses the django SimplerXMLGenerator which itself is based on the xml.sax.saxutils.XMLGenerator. I found that on my system with the following code:

$ python -c 'import xml.sax.saxutils; print xml.sax.saxutils.__file__'
/usr/lib/python2.7/xml/sax/saxutils.pyc

There is an associated py file with that. In that file I can find the XMLGenerator class and it includes an encoding paramter:

    def startDocument(self):
    self._write('<?xml version="1.0" encoding="%s"?>\n' %
                    self._encoding)

In the latest version the charset is already set to utf-8, so it produces the header that you require.

Leave a comment