【发布时间】:2015-10-24 18:45:37
【问题描述】:
我有一个 xml 文件,我在其中寻找特定标签(例如:标签 <x>),如果找到他,我会将其值替换/更新为特定文本(例如:test)。
Python 版本 3.5.0。
示例 xml 文件:
<root>
<a/>
<b>0</b>
<c/>
<x>some value</x>
</root>
这是我的代码:
from xml.etree import ElementTree as et
datafile = 'input.xml' # path to the source xml file
datafile_out = 'output.xml' # path to the updated xml
tree = et.parse(datafile)
tree.find('.//x').text ='TEST' # find <x> tag and write there value "TEST"
tree.write(datafile_out) #generating updated xml file
这是我的输出:
<root>
<a />
<b>0</b>
<c />
<x>TEST</x>
</root>
一切都按预期进行。
但我的问题是空标签中有多余的空间:<a />
在标签名称 "a" 和 "slash" 之间,输入 xml 文件中不存在。 p>
我正在处理带有很多空标签的非常大的 xml 文件,所以每个额外的空间都会使这些文件变得更大。
有什么方法可以阻止 ElementTree.write() 添加额外的空间?
注意:我想在 Python 模块中使用构建,而不是安装第三方解决方案。
非常感谢您的建议!
【问题讨论】: