如何删除空 xml 标签中多余的 space
How can I remove extra space in empty xml tags
我有一个 xml 文件,我在其中寻找特定的标签(例如:标签 <x>
),如果我找到他,我 replace/update 它对特定文本的价值(例如:测试).
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>
一切正常。
但我的问题是空标签中有额外的 space:<a />
在标签名称 "a" 和 "slash"[ 之间=50=] 输入 xml 文件中不存在。
我正在处理带有大量空标签的相当大的 xml 文件,因此每增加一个 space 都会使文件变得更大。
有什么方法可以阻止 ElementTree.write() 添加额外的 space?
注意:我想使用内置 Python 模块而不安装第三方解决方案。
非常感谢您的建议!
你试过使用正则表达式吗
举个例子:
yourXmlAsString.replaceAll(">\s*<", "><");
将删除每个 XML 元素之间的所有空格。
我有一个 xml 文件,我在其中寻找特定的标签(例如:标签 <x>
),如果我找到他,我 replace/update 它对特定文本的价值(例如:测试).
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>
一切正常。
但我的问题是空标签中有额外的 space:<a />
在标签名称 "a" 和 "slash"[ 之间=50=] 输入 xml 文件中不存在。
我正在处理带有大量空标签的相当大的 xml 文件,因此每增加一个 space 都会使文件变得更大。
有什么方法可以阻止 ElementTree.write() 添加额外的 space?
注意:我想使用内置 Python 模块而不安装第三方解决方案。
非常感谢您的建议!
你试过使用正则表达式吗
举个例子:
yourXmlAsString.replaceAll(">\s*<", "><"); 将删除每个 XML 元素之间的所有空格。