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?
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.