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

7.2. The Element() constructor

This constructor creates and returns a new Element instance.

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

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


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


If your document contains multiple XML namespaces, you can supply a namespace map that defines the namespace prefixes you would like to use when this document is converted to XML. See Section 4.3, “Namespace maps”.

If you supply this argument, it will also apply to all descendants of the created node, unless the descendant node supplies a different namespace map.


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

Here is an example of creation of a document with multiple namespaces using the nsmap keyword argument.

#!/usr/bin/env python
import sys
from lxml import etree as et

HTML_NS  =  ""
XSL_NS   =  ""
NS_MAP = {None:  HTML_NS,
          "xsl": XSL_NS}

rootName = et.QName(XSL_NS, 'stylesheet')
root = et.Element(rootName, nsmap=NS_MAP)
sheet = et.ElementTree(root)

top = et.SubElement(root, et.QName(XSL_NS, "template"), match='/')
html = et.SubElement(top, et.QName(HTML_NS, "html"))
head = et.SubElement(html, "head")
title = et.SubElement(head, "title")
title.text = "Heading title"
body = et.SubElement(html, "body")
h1 = et.SubElement(body, "h1")
h1.text = "Body heading"
p = et.SubElement(body, "p")
p.text = "Paragraph text"
sheet.write(sys.stdout, pretty_print=True)

When this root element is serialized into XML, it will look something like this:

<xsl:stylesheet xmlns:xsl=""
  <xsl:template match="/">
        <title>Heading title</title>
        <h1>Body heading</h1>
        <p>Paragraph text</p>

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"/>'