ElementTree.write 在第二遍时没有 Pretty_print
我在写入 xml 文件时遇到格式化 xml 的问题。问题是,第一次写入 xml 文件时,使用 Pretty_print=True 正确格式化了 xml。任何后续尝试附加到 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>
有什么想法吗?
I'm having an issue with formatting xml when writing to an xml file. The issue is, the first time I write to the xml file, the xml is formatted properly using pretty_print=True. Any subsequent attempts to append to the xml file are not formatted properly. The xml is written, but not formatted. My code looks like:
#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()
The first time we write to the file I get something like:
<root>
<element>
<foo>bar</foo>
</element>
</root>
Any subsequent attempts to append to this file end up looking like:
<root>
<element>
<foo>bar</foo>
</element><element><bleep>bloop</bleep></element></root>
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
常见问题解答涵盖了这个答案: 为什么漂亮的打印选项不重新格式化我的 XML 输出
这个问题之前也曾在 StackOverflow 上被问过,如 lxml 漂亮打印写入文件问题。
不幸的是,这是使用 XML 的副作用,其中空格(不幸的是)确实很重要。
The FAQ covers this answer: Why doesn't the pretty print options reformat my XML output
This question has also been asked before on StackOverflow as lxml pretty print write file problem.
It is unfortunately a side effect of using XML where whitespace (unfortunately) definitely matters.