Richard Knop
Richard Knop

Reputation: 83725

How to print Element as correct xml with xml tag?

So I have this function in my view:

from django.http import HttpResponse
from xml.etree.ElementTree import Element, SubElement, Comment, tostring

def helloworld(request):
    root_element = Element("root_element")
    comment = Comment("Hello World!!!")
    root_element.append(comment)
    foo_element = Element("foo")
    foo_element.text = "bar"
    bar_element = Element("bar")
    bar_element.text = "foo"
    root_element.append(foo_element)
    root_element.append(bar_element)
    return HttpResponse(tostring(root_element), "application/xml")

What it does it prints something like this:

<root_element><!--Hello World!!!--><foo>bar</foo><bar>foo</bar></root_element>

As you can see, it is missing the xml tag at the beginning. How to output proper XML beginning with xml declaration?

Upvotes: 2

Views: 116

Answers (1)

Alexis Huet
Alexis Huet

Reputation: 765

If you can add a dependency in your project, I suggest you to use lxml which is more complete and optimized than the basic xml module that come with Python.

For doing this, you just have to change your import statement to :

from lxml.etree import Element, SubElement, Comment, tostring

And then, you'll have a tostring() with a 'xml_declaration' option :

>>> tostring(root, xml_declaration=False)
'<root_element><!--Hello World!!!--><foo>bar</foo><bar>foo</bar></root_element>'
>>> tostring(root, xml_declaration=True)
"<?xml version='1.0' encoding='ASCII'?>\n<root_element><!--Hello World!!!--><foo>bar</foo><bar>foo</bar></root_element>"

In the standard lib, only the write() method of ElementTree have a xml_declaration option. An other solution would be to create a wrapper which use ElementTree.write() to write into a StringIO and then, to return the content of the StringIO.

Upvotes: 4

Related Questions