Force ElementTree to use closing tag

六月ゝ 毕业季﹏ 提交于 2019-12-24 18:49:31

问题


Instead of having:

<child name="George"/>

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 = ' '

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')

but this gave:

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?


回答1:


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>


来源:https://stackoverflow.com/questions/52717176/force-elementtree-to-use-closing-tag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!