ElementTree.write第二次调用时不格式化输出
我在写xml文件的时候遇到了格式化的问题。第一次写入xml文件时,使用了pretty_print=True,格式是正确的。但是之后再往这个xml文件添加内容时,格式就不对了。虽然内容是写进去了,但格式乱了。我的代码是这样的:
#does the library.xml file exist?
if os.path.isfile(libraryFile):
library = ET.ElementTree()
library.parse(libraryFile)
else:
#the library.xml does not exist at the given path
library = ET.ElementTree(project.getBoilerplateLibrary(path))
root = library.getroot()
root.append(xml) #xml is a lxml Element object
f = open(libraryFile, 'w')
library.write(f, pretty_print=True)
f.close()
第一次写入文件时,我得到的结果是这样的:
<root>
<element>
<foo>bar</foo>
</element>
</root>
但之后再往这个文件添加内容时,结果就变成了:
<root>
<element>
<foo>bar</foo>
</element><element><bleep>bloop</bleep></element></root>
有没有什么好的建议呢?
1 个回答
1
常见问题解答中有这个答案:为什么漂亮打印选项没有重新格式化我的XML输出
这个问题之前也在StackOverflow上被问过,链接是lxml漂亮打印写文件的问题.
不幸的是,这是使用XML时的一个副作用,因为在XML中,空格(很不幸)是非常重要的。