0

I am editing xml files, I ran into the problem that when changing a file in a python script, its structure is lost.

Xml file:

<?xml version="1.0" encoding="UTF-8"?>
<main>
  <element formatVersion="1.0">
    <firstValue>firstText</firstValue>
    <secondValue>secondText</secondValue>
    <thirdValue>thirdText</thirdValue>
    <errors>
      <path><![CDATA[path]]></path>
      <code_main />
    </errors>
    <reference>3</reference>
  </element>
  ....
</main>

Используя:

tree = ET.parse(xml_file).write("test.xml", encoding='utf-8', xml_declaration=True)

I lose all comments in the file, while if I compare the original file with the modified one using diff (in linux), the files are shown as completely different

Is there a way to change the xml file (my task is to add a subelement to <element>), while leaving the overall structure of the file unchanged, including comments and order.

The order and comments are fundamental in the file

UPD:

After executing the above code, I get it from the source xml in the following form:

<?xml version='1.0' encoding='utf-8'?>
<main>
  <element formatVersion="1.0">
    <firstValue>firstText</firstValue>
    <secondValue>secondText</secondValue>
    <thirdValue>thirdText</thirdValue>
    <errors>
      <path>path</path>
      <code_main />
    </errors>
    <reference>3</reference>
  </element>
</main>

Pay attention to <path>

Comments are also not saved at the same time: Source:

<main>
  <element formatVersion="1.0">
    <firstValue>firstText</firstValue>
    <secondValue>secondText</secondValue>
    <thirdValue>thirdText</thirdValue>
    <errors>
      <path><![CDATA[path]]></path>
      <!--Stt-->
      <code_main />
    </errors>
    <reference>3</reference>
  </element>
</main>

Modified:

<main>
  <element formatVersion="1.0">
    <firstValue>firstText</firstValue>
    <secondValue>secondText</secondValue>
    <thirdValue>thirdText</thirdValue>
    <errors>
      <path>path</path>
      
      <code_main />
    </errors>
    <reference>3</reference>
  </element>
</main>
mzjn
  • 48,958
  • 13
  • 128
  • 248

0 Answers0