【问题标题】:How can I remove extra space in empty xml tags如何删除空 xml 标签中的多余空间
【发布时间】: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>

一切都按预期进行。

但我的问题是空标签中有多余的空间:&lt;a /&gt; 在标签名称 "a""slash" 之间,输入 xml 文件中不存在。 p>

我正在处理带有很多空标签的非常大的 xml 文件,所以每个额外的空间都会使这些文件变得更大。

有什么方法可以阻止 ElementTree.write() 添加额外的空间?

注意:我想在 Python 模块中使用构建,而不是安装第三方解决方案。

非常感谢您的建议!

【问题讨论】:

    标签: python xml.etree


    【解决方案1】:

    您是否尝试过使用正则表达式。

    举个例子:

    yourXmlAsString.replaceAll(">\s*

    【讨论】:

    • 嗨,谢谢您的回复 :) 我确实想到了解决问题的这种方法,但是由于我是 Python 新手,我想我首先要问是否有人知道一些更合适或更优雅的解决方法这个
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多