How to set ElementTree Element text field in the constructor

Steve Schulist picture Steve Schulist · Aug 7, 2013 · Viewed 10k times · Source

How do I set the text field of of ElementTree Element from its constructor? Or, in the code below, why is the second print of root.text None?

import xml.etree.ElementTree as ET

root = ET.fromstring("<period units='months'>6</period>")
ET.dump(root)
print root.text

root=ET.Element('period', {'units': 'months'}, text='6')
ET.dump(root)
print root.text

root=ET.Element('period', {'units': 'months'})
root.text = '6'
ET.dump(root)
print root.text

Here the output:

<period units="months">6</period>
6
<period text="6" units="months" />
None
<period units="months">6</period>
6

Answer

Blender picture Blender · Aug 7, 2013

The constructor doesn't support it:

class Element(object):
    tag = None
    attrib = None
    text = None
    tail = None

    def __init__(self, tag, attrib={}, **extra):
        attrib = attrib.copy()
        attrib.update(extra)
        self.tag = tag
        self.attrib = attrib
        self._children = []

If you pass text as a keyword argument to the constructor, you will add a text attribute to your element, which is what happened in your second example.