不要折叠XML输出中的空节点 [英] do not collapse empty nodes in XML output
问题描述
我正在使用python的xml.etree.ElementTree
表示XML文档.我想将其输出为文本,但我想使空元素(没有子元素的元素)保持展开状态,而不是折叠状态.例如,我想要这个:
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>
代替此:
<element />
我目前正在使用ElementTree.tostring
,但是我愿意使用任何其他内置的python模块或函数来序列化文档,只要我可以很容易地将其与ElementTree对象一起使用即可.
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.
推荐答案
You can pass method="html"
to the tostring()
call.
演示:
>>> 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>
这篇关于不要折叠XML输出中的空节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!