do not collapse empty nodes in XML output

房东的猫 提交于 2019-12-11 02:18:16

问题


I'm using python's xml.etree.ElementTree to represent an XML document. I want to output it to text but I want to keep empty elements (elements with no children) expanded, instead of collapsed. E.g., I want this:

<element></element>

Instead of this:

<element />

I'm currently using ElementTree.tostring, but I'm willing to use any other built-in python modules or functions to serialize the document, as long as I can pretty easily use an ElementTree object with it.

FYI, the reason I want to keep the elements expanded is because I want to more easily diff the output with output from a third party program which doesn't collapse empty elements.


回答1:


You can pass method="html" to the tostring() call.

Demo:

>>> import xml.etree.ElementTree as etree
>>> data = """
... <root>
...     <person/>
...     <person></person>
... </root>
... """
>>> tree = etree.fromstring(data)
>>> print etree.tostring(tree, method="html")
<root>
    <person></person>
    <person></person>
</root>



回答2:


Just use: ElementTree.tostring(element, short_empty_elements=False)



来源:https://stackoverflow.com/questions/23475104/do-not-collapse-empty-nodes-in-xml-output

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!