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

nsmap

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.

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

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  =  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"
XSL_NS   =  "http://www.w3.org/1999/XSL/Transform"
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="http://www.w3.org/1999/XSL/Transform"
    xmlns="http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  <xsl:template match="/">
    <html>
      <head>
        <title>Heading title</title>
      </head>
      <body>
        <h1>Body heading</h1>
        <p>Paragraph text</p>
      </body>
    </html>
  </xsl:template>
</xsl:stylesheet>

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