Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ElementTree.write doesn't pretty_print on second pass

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?

like image 506
Greg Avatar asked Jan 25 '26 18:01

Greg


1 Answers

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.

like image 165
X-Istence Avatar answered Jan 27 '26 07:01

X-Istence



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!