所以我认为我有这个功能:
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")
它的作用是打印如下内容:
<root_element><!--Hello World!!!--><foo>bar</foo><bar>foo</bar></root_element>
如您所见,它缺少开头的 xml 标记。如何以 xml 声明开头输出正确的 XML?