Search code examples
pythonxmlstringpython-2.7elementtree

Force ElementTree to use closing tag


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?


Solution

  • 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>