Python - Modifying xml file erases comments [duplicate]




This question already has an answer here:




Let's say my xml file looks like this:



<Products>
<Product name="first" />

<!-- some comment -->
<Product name="second" />

<Product name="third" />
</Products>


And my script:



import xml.etree.ElementTree as ET

tree = ET.parse('test.xml')
root = tree.getroot()

elem = ET.Element('Product')
elem.attrib['name'] = 'fourth'

root.append(elem)

tree.write('test.xml')


The resulting xml will look like this:



<Products>
<Product name="first" />

<Product name="second" />

<Product name="third" />
<Product name="fourth" /></Products>


First, the formatting is a little off (spaces and new lines), but the thing that bothers me is that the comment line in not in the new file.


Is there a way to modify a xml file without losing those?


No comments:

Post a Comment