不要再使用:
<child name="George"/>
在XML文件中,我需要有:
<child name="George"></child>
一个丑陋的解决方案是将空格作为文本写入(不是空字符串,因为它会忽略它):
import xml.etree.ElementTree as ET
ch = ET.SubElement(parent, 'child')
ch.set('name', 'George')
ch.text = ' '
那么,由于我使用的是Python 2.7,我阅读了Python etree控制空标签格式,并尝试使用html方法,如下所示:
ch = ET.tostring(ET.fromstring(ch), method='html')
但是这给了:
TypeError: Parse() argument 1 must be string or read-only buffer, not Element
我不确定该怎么解决这个问题,请问你有什么建议吗?
ch.text = ''
(空字符串)有效。请参见https://dev59.com/SBL6s4cB2Jgan1zn9kZQ#47817478。 - mzjn