2

所以我认为我有这个功能:

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?

4

1 回答 1

4

如果你可以在你的项目中添加依赖,我建议你使用lxml,它比 Python 自带的基本 xml 模块更完善和优化。

为此,您只需将导入语句更改为:

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

然后,您将拥有一个带有 'xml_declaration' 选项的 tostring() :

>>> 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>"

在标准库中,只有 ElementTree 的 write() 方法有 xml_declaration 选项。另一种解决方案是创建一个包装器,它使用 ElementTree.write() 写入 StringIO,然后返回 StringIO 的内容。

于 2012-08-01T15:26:13.510 回答