Next / Previous / Contents / TCC Help System / NM Tech homepage

6.2. The Element() constructor

This constructor creates and returns a new Element instance.

etree.Element ( tag, attrib={}, **extras )
tag

A string containing the name of the element to be created.

attrib

A dictionary containing attribute names and values to be added to the element. The default is to have no attributes.

extras

Any keyword arguments of the form name=value that you supply to the constructor are added to the element's attributes. For example, this code:

newReed = etree.Element ( 'reed', pitch='440', id='a4' )

will produce an element that looks like this:

<reed pitch='440' id='a4'/>

If you are working with multiple namespaces, you may also include an nsmap keyword argument defining your preferred namespace prefixes. For more on the nsmap argument, see Section 6.3, “The ElementTree() constructor”.

There is one minor pathology of this constructor. If you pass in a pre-constructed dictionary as the attrib argument, and you also supply keyword arguments, the values of the keyword arguments will be added into that dictionary as if you had used the .update() method on the attrib dictionary. Here is a conversational example showing this side effect:

>>> from lxml import etree
>>> d = { 'name': 'Clem', 'clan': 'bozo' }
>>> clownElt = etree.Element ( 'clown', d, attitude='bad' )
>>> d
{'clan': 'bozo', 'attitude': 'bad', 'name': 'Clem'}
>>> etree.tostring ( clownElt )
'<clown clan="bozo" attitude="bad" name="Clem"/>'
>>>