强制ElementTree使用结束标记 [英] Force ElementTree to use closing tag
本文介绍了强制ElementTree使用结束标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
而不是:
<child name="George"/>
在XML文件中,我需要:
at the XML file, I need to have:
<child name="George"></child>
一个丑陋的解决方法是将空白写为文本(不是空字符串,因为它将忽略它) ):
An ugly workaround is to write a whitespace as text (not an empty string, as it will ignore it):
import xml.etree.ElementTree as ET
ch = ET.SubElement(parent, 'child')
ch.set('name', 'George')
ch.text = ' '
然后,由于我使用的是Python 2.7,因此我读 Python etree控件为空标记格式,并尝试了html方法,如下所示:
Then, since I am using Python 2.7, I read Python etree control empty tag format, and tried the html method, like so:
ch = ET.tostring(ET.fromstring(ch), method='html')
但这给了:
TypeError: Parse() argument 1 must be string or read-only buffer, not Element
,我不确定该如何解决。有任何想法吗?
and I am not sure what what I should do to fix it. Any ideas?
推荐答案
如果您这样做的话,在2.7中应该可以正常工作:
If you do it like this it should work fine in 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>
这篇关于强制ElementTree使用结束标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文