强制 ElementTree 使用结束标签
Force ElementTree to use closing tag
而不是:
<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 control empty tag format,并尝试了html方法,如下所示:
ch = ET.tostring(ET.fromstring(ch), method='html')
但这给了:
TypeError: Parse() argument 1 must be string or read-only buffer, not Element
而且我不确定应该如何修复它。有什么想法吗?
如果你这样做它应该在 2.7 中工作正常:
from xml.etree.ElementTree import Element, SubElement, tostring
parent = Element('parent')
ch = SubElement(parent, 'child')
ch.set('name', 'George')
print tostring(parent, method='html')
#<parent><child name="George"></child></parent>
print tostring(child, method='html')
#<child name="George"></child>
而不是:
<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 control empty tag format,并尝试了html方法,如下所示:
ch = ET.tostring(ET.fromstring(ch), method='html')
但这给了:
TypeError: Parse() argument 1 must be string or read-only buffer, not Element
而且我不确定应该如何修复它。有什么想法吗?
如果你这样做它应该在 2.7 中工作正常:
from xml.etree.ElementTree import Element, SubElement, tostring
parent = Element('parent')
ch = SubElement(parent, 'child')
ch.set('name', 'George')
print tostring(parent, method='html')
#<parent><child name="George"></child></parent>
print tostring(child, method='html')
#<child name="George"></child>