在写入xml文件时,我遇到了格式化xml的问题。问题是,当我第一次写入xml文件时,xml使用pretty_print=True进行了正确的格式化。任何后续尝试追加到xml文件的尝试都未正确格式化。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>有什么想法吗?
发布于 2011-06-11 17:17:02
常见问题解答涵盖了以下答案:Why doesn't the pretty print options reformat my XML output
这个问题以前也曾在StackOverflow上以lxml pretty print write file problem的身份被问过。
不幸的是,这是使用XML的副作用,在这种情况下,空格(不幸的)确实很重要。
https://stackoverflow.com/questions/6311699
复制相似问题