我使用 Python3.5 中的
xml
库来 reading 和 writing 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>
<movie>
标签现在具有属性了。<value>
标签现在具有更少的属性。请注意,“xml 包”和“
xml
库”是不明确的。标准库中有几个与 XML 相关的模块:https://docs.python.org/3/library/xml.html.
为什么要修改?
ElementTree 将命名空间声明移动到根元素,并删除文档中实际未使用的命名空间声明。
ElementTree为什么要这么做?我不知道,但也许这是一种使实现更简单的方法。
如何防止这种情况发生?例如我只想替换特定标签或其在相当复杂的 xml 文件中的值,而不丢失任何其他信息。
我认为没有办法阻止这种情况。这个问题之前已经提出过。这是两个非常相似的问题:
我的建议是使用 lxml 而不是 ElementTree。使用 lxml,命名空间声明将保留在原始文件中出现的位置。
1号线已经消失了。
该行是 XML 声明。建议但不强制拥有一个。
如果您始终需要 XML 声明,请在
xml_declaration=True
方法调用中使用 write()
。