Python 如何删除空xml标记中的额外空间

Python 如何删除空xml标记中的额外空间,python,xml.etree,Python,Xml.etree,我有一个xml文件,我在其中查找特定的标记(例如:tag),如果我找到了它,我会将其值替换/更新为特定的文本(例如: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文件,我在其中查找特定的标记(例如:tag
),如果我找到了它,我会将其值替换/更新为特定的文本(例如: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>

0
一些价值
这是我的代码:

<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>
从xml.etree导入ElementTree作为et
数据文件='input.xml'#源xml文件的路径
datafile_out='output.xml'#更新的xml的路径
tree=et.parse(数据文件)
tree.find('.//x').text='TEST'#查找标记并在其中写入值“TEST”
write(数据文件输出)#生成更新的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>

0
试验
一切正常

但我的问题是空标记中有额外的空间:
在标记名“a”“slash”之间,输入xml文件中不存在该标记名

我正在处理相当大的xml文件,其中有很多空标记,因此每增加一个空间,这些文件就会变得更大

是否有任何可能的方法停止ElementTree.write()以添加额外的空间

注意:我希望使用内置Python模块,而不是安装第三方解决方案


非常感谢你的建议

您尝试过使用正则表达式吗

例如:


yourXmlAsString.replaceAll(“>\s*Hi,感谢您的回复:”)我确实想到了解决这个问题的方法,但由于我是Python新手,我想我首先问一下是否有人知道更合适或优雅的方法来解决这个问题