Python - 打印漂亮的 XML,为空标签文本创建开始和结束标签 [英] Python - print pretty XML create opening and closing tags for empty tags text
问题描述
我正在编写一个 python 应用程序,它创建一个 ElementTree (XML),然后使用 minidom 的 toprettyxml() 将其写入文件;
I'm writing a python application that creates an ElementTree (XML) and then writing it to a file, using minidom's toprettyxml();
final_tree = minidom.parseString(ET.tostring(root))
fdout.write(final_tree.toprettyxml(indent = ' ')
问题是,我没有附加任何文本的标签只有一个标签,例如:
The problem is, that tags which i'm not appending any text comes out with only one tag, for example:
<sometag/>
我希望它是:
<sometag>
</sometag>
我想在不解析整个字符串(没有正则表达式)的情况下做到这一点.有人熟悉这种方式吗?谢谢.
I want to do it without parsing the whole string (without regex). Is anybody familiar with such way? Thanks.
推荐答案
minidom.py
中的行为是硬连接的(查看 writexml()
方法在 class Element
中).它并不意味着要更改,但对于当前实现,您可以像这样修补它:
The behavior is hard-wired in minidom.py
(have a look at writexml()
method in class Element
). It is not meant to be changed, but for the current implementation you can monkey-patch it like this:
from xml.dom import minidom
t = minidom.parseString('<a><b></b></a>')
def patcher(method):
def patching(self, *args, **kwargs):
old = self.childNodes
try:
if not self.childNodes:
class Dummy(list):
def __nonzero__(self): # Python2
return True
def __bool__(self): # Python3
return True
old, self.childNodes = self.childNodes, Dummy([])
return method(self, *args, **kwargs)
finally:
self.childNodes = old
return patching
t.firstChild.__class__.writexml = patcher(t.firstChild.__class__.writexml)
print t.toprettyxml()
但我当然不能推荐这样的黑客.
But of course I cannot recommend such a hack.
这篇关于Python - 打印漂亮的 XML,为空标签文本创建开始和结束标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!