Skip to content
Advertisement

Python how to keep the XML comment exist after write a new value using Python?

I have an XML file then need to update some value. My XML file contains the comment. I would like to keep the comment after writing the XML, but it disappeared.

Here is my XML:

JavaScript

This is the value that I need to update

JavaScript

become this:

JavaScript

My code:

JavaScript

The output of the test.xml file become this. the comment and <?xml version="1.0" encoding="UTF-8"?> dissapeared.

JavaScript

BUT my expectation output, the structure and the comment still the same as before update the value like this:

JavaScript

Advertisement

Answer

  1. Use ET.XMLParser to preserve comments
  2. Use encoding and xml_declaration arguments in write() function to write xml declaration Try the following code:
JavaScript

you can also avoid variable read and just use tree:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement