为什么 xml 包修改了我在 Python3 中的 xml 文件?

Why does xml package modify my xml file in Python3?

我使用 Python3.5 中的 xml 库进行 阅读 写作 和 xml-文件。我不修改文件。只需打开并写入。但是库修改了文件。

  1. 为什么要修改?
  2. 我该如何防止这种情况发生?例如我只想在不丢失任何其他信息的情况下替换特定标签或其在相当复杂的 xml 文件中的值。

这是示例文件

<?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>

这是代码

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

xml-文件变成了这个

<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>

请注意 "xml package" 和 "the xml library" 是不明确的。标准库中有几个XML相关的模块:https://docs.python.org/3/library/xml.html.

Why is it modified?

ElementTree 将命名空间声明移至根元素,并删除文档中实际未使用的命名空间。

ElementTree 为什么要这样做?我不知道,但也许这是一种使实施更简单的方法。

How can I prevent this? e.g. I just want to replace specific tag or it's value in a quite complex xml-file without loosing any other informations.

我认为没有办法阻止这种情况。这个问题之前有人提出过。这里有两个非常相似的问题没有答案:

  • How do I parse and write XML using Python's ElementTree without moving namespaces around?

我的建议是使用 lxml 而不是 ElementTree。使用 lxml,命名空间声明将保留在原始文件中出现的位置。

Line 1 is gone.

那一行是 XML 声明。建议但不强制拥有一个。

如果您始终需要 XML 声明,请在 write() 方法调用中使用 xml_declaration=True