Why does an xml package modify my xml file in Python3?

I am using a library xmlin Python3.5 to read and write an xml file. I do not modify the file. Just open and write. But the library modifies the file.

  • Why is this changed?
  • How can I prevent this? for example, I just want to replace a specific tag or its value in a rather complex xml file without losing any information.

This is an example file.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<movie>
    <title>Der Eisbär</title>
    <ids>
        <entry>
            <key>tmdb</key>
            <value xsi:type="xs:int" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">9321</value>
        </entry>
        <entry>
            <key>imdb</key>
            <value xsi:type="xs:string" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">tt0167132</value>
        </entry>
    </ids>
</movie>

This is the code

import xml.etree.ElementTree as ET
tree = ET.parse('x.nfo')
tree.write('y.nfo', encoding='utf-8')

And the xml file becomes this

<movie xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <title>Der Eisbär</title>
    <ids>
        <entry>
            <key>tmdb</key>
            <value xsi:type="xs:int">9321</value>
        </entry>
        <entry>
            <key>imdb</key>
            <value xsi:type="xs:string">tt0167132</value>
        </entry>
    </ids>
</movie>
  • Line 1 is gone.
  • <movie> -tag on line 2 now has attributes.
  • <value> -tag on line 7 and 11 now has fewer attributes.
+4
source share
1 answer

, "xml-" " xml" . XML : https://docs.python.org/3/library/xml.html.

?

ElementTree , , , .

ElementTree ? , , , .

? xml , .

, . . :

- lxml ElementTree. lxml , .

1 .

XML. , .

XML, xml_declaration=True write().

+3

Source: https://habr.com/ru/post/1684855/


All Articles