I try to insert a tag in a big xml file. And I only want change that line that I insert, not all the other lines. Because the logic, when I must insert the lines, is not that simple, I have to use a xml parser. But the parser that I used, changed the other lines as well.
original file:
<?xml version='1.0' encoding='UTF-8'?>
<tag>
<!-- Comment with ÄÜÖ -->
<name>test</name>
<name></name>
</tag>
desired file:
<?xml version='1.0' encoding='UTF-8'?>
<tag>
<!-- Comment with ÄÜÖ -->
<name>test</name>
<name>test2</name>
<name></name>
</tag>
lxml for example shows the character entities and automatically shortens empty tags after saving.
lxml result:
<tag>
<!-- Comment with ÄÜÖ -->
<name>test</name>
<name>test2</name>
<name />
</tag>
lxml code:
from lxml import etree
with open('org.xml', 'r') as xml_file:
xml_tree = etree.parse(xml_file)
// adding/manipulating xml
// ...
// saving xml
with open('final.xml', 'wb') as final_file:
final_file.write(etree.tostring(xml_tree))