gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 01:56:23 24 4
gpt4 key购买 nike

我使用 xml Python3.5 中用于读取写入 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>
  • 第 1 行不见了。
  • <movie> -第 2 行中的标记现在具有属性。
  • <value> - 第 7 行和第 11 行中的标记现在具有更少的属性。

最佳答案

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

Why is it modified?

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

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.

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

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

Line 1 is gone.

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

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

关于xml - 为什么 xml 包会在 Python3 中修改我的 xml 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45990761/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com