• January 26, 2023

Python Lxml Etree

The lxml.etree Tutorial

The lxml.etree Tutorial

Author:
Stefan Behnel
This is a tutorial on XML processing with It briefly
overviews the main concepts of the ElementTree API, and some simple
enhancements that make your life as a programmer easier.
For a complete reference of the API, see the generated API
documentation.
Contents
The Element class
Elements are lists
Elements carry attributes as a dict
Elements contain text
Using XPath to find text
Tree iteration
Serialisation
The ElementTree class
Parsing from strings and files
The fromstring() function
The XML() function
The parse() function
Parser objects
Incremental parsing
Event-driven parsing
Namespaces
The E-factory
ElementPath
A common way to import is as follows:
>>> from lxml import etree
If your code only uses the ElementTree API and does not rely on any
functionality that is specific to, you can also use (any part
of) the following import chain as a fall-back to the original ElementTree:
try:
from lxml import etree
print(“running with “)
except ImportError:
# Python 2. 5
import as etree
print(“running with cElementTree on Python 2. 5+”)
print(“running with ElementTree on Python 2. 5+”)
# normal cElementTree install
import cElementTree as etree
print(“running with cElementTree”)
# normal ElementTree install
import elementtree. ElementTree as etree
print(“running with ElementTree”)
print(“Failed to import ElementTree from any known place”)
To aid in writing portable code, this tutorial makes it clear in the examples
which part of the presented API is an extension of over the
original ElementTree API, as defined by Fredrik Lundh’s ElementTree
library.
An Element is the main container object for the ElementTree API. Most of
the XML tree functionality is accessed through this class. Elements are
easily created through the Element factory:
>>> root = etree. Element(“root”)
The XML tag name of elements is accessed through the tag property:
Elements are organised in an XML tree structure. To create child elements and
add them to a parent element, you can use the append() method:
>>> ( etree. Element(“child1”))
However, this is so common that there is a shorter and much more efficient way
to do this: the SubElement factory. It accepts the same arguments as the
Element factory, but additionally requires the parent as first argument:
>>> child2 = bElement(root, “child2”)
>>> child3 = bElement(root, “child3”)
To see that this is really XML, you can serialise the tree you have created:
>>> print(string(root, pretty_print=True))





To make the access to these subelements easy and straight forward,
elements mimic the behaviour of normal Python lists as closely as
possible:
>>> child = root[0]
>>> print()
child1
>>> print(len(root))
3
>>> (root[1]) # only!
1
>>> children = list(root)
>>> for child in root:… print()
child2
child3
>>> (0, etree. Element(“child0”))
>>> start = root[:1]
>>> end = root[-1:]
>>> print(start[0])
child0
>>> print(end[0])
Prior to ElementTree 1. 3 and lxml 2. 0, you could also check the truth value of
an Element to see if it has children, i. e. if the list of children is empty:
if root: # this no longer works!
print(“The root element has children”)
This is no longer supported as people tend to expect that a “something”
evaluates to True and expect Elements to be “something”, may they have
children or not. So, many users find it surprising that any Element
would evaluate to False in an if-statement like the above. Instead,
use len(element), which is both more explicit and less error prone.
>>> print(element(root)) # test if it’s some kind of Element
True
>>> if len(root): # test if it has children… print(“The root element has children”)
The root element has children
There is another important case where the behaviour of Elements in lxml
(in 2. 0 and later) deviates from that of lists and from that of the
original ElementTree (prior to version 1. 3 or Python 2. 7/3. 2):
>>> root[0] = root[-1] # this moves the element in!
In this example, the last element is moved to a different position,
instead of being copied, i. it is automatically removed from its
previous position when it is put in a different place. In lists,
objects can appear in multiple positions at the same time, and the
above assignment would just copy the item reference into the first
position, so that both contain the exact same item:
>>> l = [0, 1, 2, 3]
>>> l[0] = l[-1]
>>> l
[3, 1, 2, 3]
Note that in the original ElementTree, a single Element object can sit
in any number of places in any number of trees, which allows for the same
copy operation as with lists. The obvious drawback is that modifications
to such an Element will apply to all places where it appears in a tree,
which may or may not be intended.
The upside of this difference is that an Element in always
has exactly one parent, which can be queried through the getparent()
method. This is not supported in the original ElementTree.
>>> root is root[0]. getparent() # only!
If you want to copy an element to a different position in,
consider creating an independent deep copy using the copy module
from Python’s standard library:
>>> from copy import deepcopy
>>> element = etree. Element(“neu”)
>>> ( deepcopy(root[1]))
>>> print(element[0])
>>> print([ for c in root])
[‘child3’, ‘child1’, ‘child2′]
The siblings (or neighbours) of an element are accessed as next and previous
elements:
>>> root[0] is root[1]. getprevious() # only!
>>> root[1] is root[0]. getnext() # only!
XML elements support attributes. You can create them directly in the Element
factory:
>>> root = etree. Element(“root”, interesting=”totally”)
>>> string(root)
b’
Attributes are just unordered name-value pairs, so a very convenient way
of dealing with them is through the dictionary-like interface of Elements:
>>> print((“interesting”))
totally
>>> print((“hello”))
None
>>> (“hello”, “Huhu”)
Huhu
b’
>>> sorted(())
[‘hello’, ‘interesting’]
>>> for name, value in sorted(()):… print(‘%s =%r’% (name, value))
hello = ‘Huhu’
interesting = ‘totally’
For the cases where you want to do item lookup or have other reasons for
getting a ‘real’ dictionary-like object, e. g. for passing it around,
you can use the attrib property:
>>> attributes =
>>> print(attributes[“interesting”])
>>> print((“no-such-attribute”))
>>> attributes[“hello”] = “Guten Tag”
>>> print(attributes[“hello”])
Guten Tag
Note that attrib is a dict-like object backed by the Element itself.
This means that any changes to the Element are reflected in attrib
and vice versa. It also means that the XML tree stays alive in memory
as long as the attrib of one of its Elements is in use. To get an
independent snapshot of the attributes that does not depend on the XML
tree, copy it into a dict:
>>> d = dict()
[(‘hello’, ‘Guten Tag’), (‘interesting’, ‘totally’)]
Elements can contain text:
>>> = “TEXT”
TEXT
b’TEXT
In many XML documents (data-centric documents), this is the only place where
text can be found. It is encapsulated by a leaf tag at the very bottom of the
tree hierarchy.
However, if XML is used for tagged text documents such as (X)HTML, text can
also appear between different elements, right in the middle of the tree:
Hello
World
Here, the
tag is surrounded by text. This is often referred to as
document-style or mixed-content XML. Elements support this through their
tail property. It contains the text that directly follows the element, up
to the next element in the XML tree:
>>> html = etree. Element(“html”)
>>> body = bElement(html, “body”)
>>> string(html)
b’TEXT‘
>>> br = bElement(body, “br”)
b’TEXT

>>> = “TAIL”
b’TEXT
TAIL‘
The two properties and are enough to represent any
text content in an XML document. This way, the ElementTree API does
not require any special text nodes in addition to the Element
class, that tend to get in the way fairly often (as you might know
from classic DOM APIs).
However, there are cases where the tail text also gets in the way.
For example, when you serialise an Element from within the tree, you
do not always want its tail text in the result (although you would
still want the tail text of its children). For this purpose, the
tostring() function accepts the keyword argument with_tail:
>>> string(br)
b’
TAIL’
>>> string(br, with_tail=False) # only!
b’

If you want to read only the text, i. without any intermediate
tags, you have to recursively concatenate all text and tail
attributes in the correct order. Again, the tostring() function
comes to the rescue, this time using the method keyword:
>>> string(html, method=”text”)
b’TEXTTAIL’
Another way to extract the text content of a tree is XPath, which
also allows you to extract the separate text chunks into a list:
>>> print((“string()”)) # only!
TEXTTAIL
>>> print((“//text()”)) # only!
[‘TEXT’, ‘TAIL’]
If you want to use this more often, you can wrap it in a function:
>>> build_text_list = (“//text()”) # only!
>>> print(build_text_list(html))
Note that a string result returned by XPath is a special ‘smart’
object that knows about its origins. You can ask it where it came
from through its getparent() method, just as you would with
Elements:
>>> texts = build_text_list(html)
>>> print(texts[0])
>>> parent = texts[0]. getparent()
body
>>> print(texts[1])
TAIL
>>> print(texts[1]. getparent())
br
You can also find out if it’s normal text content or tail text:
>>> print(texts[0]. is_text)
>>> print(texts[1]. is_text)
False
>>> print(texts[1]. is_tail)
While this works for the results of the text() function, lxml will
not tell you the origin of a string value that was constructed by the
XPath functions string() or concat():
>>> stringify = (“string()”)
>>> print(stringify(html))
>>> print(stringify(html). getparent())
For problems like the above, where you want to recursively traverse the tree
and do something with its elements, tree iteration is a very convenient
solution. Elements provide a tree iterator for this purpose. It yields
elements in document order, i. in the order their tags would appear if you
serialised the tree to XML:
>>> bElement(root, “child”) = “Child 1”
>>> bElement(root, “child”) = “Child 2”
>>> bElement(root, “another”) = “Child 3”
Child 1
Child 2
Child 3
>>> for element in ():… print(“%s -%s”% (, ))
root – None
child – Child 1
child – Child 2
another – Child 3
If you know you are only interested in a single tag, you can pass its name to
iter() to have it filter for you. Starting with lxml 3. 0, you can also
pass more than one tag to intercept on multiple tags during iteration.
>>> for element in (“child”):… print(“%s -%s”% (, ))
>>> for element in (“another”, “child”):… print(“%s -%s”% (, ))
By default, iteration yields all nodes in the tree, including
ProcessingInstructions, Comments and Entity instances. If you want to
make sure only Element objects are returned, you can pass the
Element factory as tag parameter:
>>> ((“#234”))
>>> (mment(“some comment”))
>>> for element in ():… if isinstance(, basestring): # or ‘str’ in Python 3… print(“%s -%s”% (, ))… else:… print(“SPECIAL:%s -%s”% (element, ))
SPECIAL: ê – ê
SPECIAL: – some comment
>>> for element in (tag=etree. Element):… print(“%s -%s”% (, ))
>>> for element in ():… print()
ê
Note that passing a wildcard “*” tag name will also yield all
Element nodes (and only elements).
In, elements provide further iterators for all directions in the
tree: children, parents (or rather ancestors) and siblings.
Serialisation commonly uses the tostring() function that returns a
string, or the () method that writes to a file, a
file-like object, or a URL (via FTP PUT or HTTP POST). Both calls accept
the same keyword arguments like pretty_print for formatted output
or encoding to select a specific output encoding other than plain
ASCII:
>>> root = (‘‘)
b’
>>> print(string(root, xml_declaration=True))


>>> print(string(root, encoding=’iso-8859-1′))




Note that pretty printing appends a newline at the end.
For more fine-grained control over the pretty-printing, you can add
whitespace indentation to the tree before serialising it, using the
indent() function (added in lxml 4. 5):
>>> root = (‘n‘)
>>> print(string(root))


>>> (root)
>>>
‘n ‘
>>> root[0]
>>> (root, space=” “)
>>> (root, space=”t”)
ntnttntn
In lxml 2. 0 and later (as well as ElementTree 1. 3), the serialisation
functions can do more than XML serialisation. You can serialise to
HTML or extract the text content by passing the method keyword:
>>> root = (… ‘

Hello
World

‘)
>>> string(root) # default: method = ‘xml’
b’

Hello
World


>>> string(root, method=’xml’) # same as above
>>> string(root, method=’html’)
b’

Hello
World


>>> print(string(root, method=’html’, pretty_print=True))


Hello
World



>>> string(root, method=’text’)
b’HelloWorld’
As for XML serialisation, the default encoding for plain text
serialisation is ASCII:
>>> br = next((‘br’)) # get first result of iteration
>>> = u’Wxf6rld’
>>> string(root, method=’text’) # doctest: +ELLIPSIS
Traceback (most recent call last):…
UnicodeEncodeError: ‘ascii’ codec can’t encode character u’xf6’…
>>> string(root, method=’text’, encoding=”UTF-8″)
b’HelloWxc3xb6rld’
Here, serialising to a Python unicode string instead of a byte string
might become handy. Just pass the name ‘unicode’ as encoding:
>>> string(root, encoding=’unicode’, method=’text’)
u’HelloWxf6rld’
The W3C has a good article about the Unicode character set and
character encodings.
An ElementTree is mainly a document wrapper around a tree with a
root node. It provides a couple of methods for serialisation and
general document handling.
>>> root = (”’… ]>… &tasty;… ”’)
>>> tree = etree. ElementTree(root)
>>> print(cinfo. xml_version)
1. 0
>>> print(ctype)

>>> lic_id = ‘-//W3C//DTD XHTML 1. 0 Transitional//EN’
>>> stem_url = ”

An ElementTree is also what you get back when you call the
parse() function to parse files or file-like objects (see the
parsing section below).
One of the important differences is that the ElementTree class
serialises as a complete document, as opposed to a single Element.
This includes top-level processing instructions and comments, as well
as a DOCTYPE and other DTD content in the document:
>>> print(string(tree)) # lxml 1. 3. 4 and later
]>
parsnips
In the original implementation and in lxml
up to 1. 3, the output looks the same as when serialising only
the root Element:
>>> print(string(troot()))
This serialisation behaviour has changed in lxml 1. 4. Before,
the tree was serialised without DTD content, which made lxml
lose DTD information in an input-output cycle.
supports parsing XML in a number of ways and from all
important sources, namely strings, files, URLs (/ftp) and
file-like objects. The main parse functions are fromstring() and
parse(), both called with the source as first argument. By
default, they use the standard parser, but you can always pass a
different parser as second argument.
The fromstring() function is the easiest way to parse a string:
>>> some_xml_data = “data
>>> root = omstring(some_xml_data)
root
b’data
The XML() function behaves like the fromstring() function, but is
commonly used to write XML literals right into the source:
>>> root = (“data“)
There is also a corresponding function HTML() for HTML literals.
>>> root = (“

data

“)
b’

data


The parse() function is used to parse from files and file-like objects.
As an example of such a file-like object, the following code uses the
BytesIO class for reading from a string instead of an external file.
That class comes from the io module in Python 2. 6 and later. In older
Python versions, you will have to use the StringIO class from the
StringIO module. However, in real life, you would obviously avoid
doing this all together and use the string parsing functions above.
>>> from io import BytesIO
>>> some_file_or_file_like_object = BytesIO(b”data“)
>>> tree = (some_file_or_file_like_object)
>>> string(tree)
Note that parse() returns an ElementTree object, not an Element object as
the string parser functions:
>>> root = troot()
The reasoning behind this difference is that parse() returns a
complete document from a file, while the string parsing functions are
commonly used to parse XML fragments.
The parse() function supports any of the following sources:
an open file object (make sure to open it in binary mode)
a file-like object that has a (byte_count) method returning
a byte string on each call
a filename string
an HTTP or FTP URL string
Note that passing a filename or URL is usually faster than passing an
open file or file-like object. However, the HTTP/FTP client in libxml2
is rather simple, so things like HTTP authentication require a dedicated
URL request library, e. urllib2 or requests. These libraries
usually provide a file-like object for the result that you can parse
from while the response is streaming in.
By default, uses a standard parser with a default setup. If
you want to configure the parser, you can create a new instance:
>>> parser = etree. XMLParser(remove_blank_text=True) # only!
This creates a parser that removes empty text between tags while parsing,
which can reduce the size of the tree and avoid dangling tail text if you know
that whitespace-only content is not meaningful for your data. An example:
>>> root = (“ “, parser)
b’

Note that the whitespace content inside the tag was not removed, as
content at leaf elements tends to be data content (even if blank). You can
easily remove it in an additional step by traversing the tree:
>>> for element in (“*”):… if is not None and not ():… = None
b’

See help(etree. XMLParser) to find out about the available parser options.
provides two ways for incremental step-by-step parsing. One is
through file-like objects, where it calls the read() method repeatedly.
This is best used where the data arrives from a source like urllib or any
other file-like object that can provide data on request. Note that the parser
will block and wait until data becomes available in this case:
>>> class DataSource:… data = [ b”<", b"a/", b"><", b"/root>“]… def read(self, requested_size):… try:… return (0)… except IndexError:… return b”
>>> tree = (DataSource())
b’

The second way is through a feed parser interface, given by the feed(data)
and close() methods:
>>> parser = etree. XMLParser()
>>> (“>> (“t><") >>> (“a/”)
>>> (“><") >>> (“/root>”)
>>> root = ()
Here, you can interrupt the parsing process at any time and continue it later
on with another call to the feed() method. This comes in handy if you
want to avoid blocking calls to the parser, e. in frameworks like Twisted,
or whenever data comes in slowly or in chunks and you want to do other things
while waiting for the next chunk.
After calling the close() method (or when an exception was raised
by the parser), you can reuse the parser by calling its feed()
method again:
>>> (““)
b’
Sometimes, all you need from a document is a small fraction somewhere deep
inside the tree, so parsing the whole tree into memory, traversing it and
dropping it can be too much overhead. supports this use case
with two event-driven parser interfaces, one that generates parser events
while building the tree (iterparse), and one that does not build the tree
at all, and instead calls feedback methods on a target object in a SAX-like
fashion.
Here is a simple iterparse() example:
>>> some_file_like = BytesIO(b”
data“)
>>> for event, element in erparse(some_file_like):… print(“%s, %4s, %s”% (event,, ))
end, a, data
end, root, None
By default, iterparse() only generates events when it is done parsing an
element, but you can control this through the events keyword argument:
>>> for event, element in erparse(some_file_like,… events=(“start”, “end”)):… print(“%5s, %4s, %s”% (event,, ))
start, root, None
start, a, data
Note that the text, tail, and children of an Element are not necessarily present
yet when receiving the start event. Only the end event guarantees
that the Element has been parsed completely.
It also allows you to () or modify the content of an Element to
save memory. So if you parse a large tree and you want to keep memory
usage small, you should clean up parts of the tree that you no longer
need. The keep_tail=True argument to () makes sure that
(tail) text content that follows the current element will not be touched.
It is highly discouraged to modify any content that the parser may not
have completely read through yet.
>>> some_file_like = BytesIO(… b”data“)
>>> for event, element in erparse(some_file_like):… if == ‘b’:… print()… elif == ‘a’:… print(“** cleaning up the subtree”)… (keep_tail=True)
data
** cleaning up the subtree
A very important use case for iterparse() is parsing large
generated XML files, e. database dumps. Most often, these XML
formats only have one main data item element that hangs directly below
the root node and that is repeated thousands of times. In this case,
it is best practice to let do the tree building and only to
intercept on exactly this one Element, using the normal tree API
for data extraction.
>>> xml_file = BytesIO(b”’… ABCabcMORE DATAmore dataXYZxyz… ”’)
>>> for _, element in erparse(xml_file, tag=’a’):… print(‘%s –%s’% (ndtext(‘b’), element[1]))… (keep_tail=True)
ABC — abc
MORE DATA — more data
XYZ — xyz
If, for some reason, building the tree is not desired at all, the
target parser interface of can be used. It creates
SAX-like events by calling the methods of a target object. By
implementing some or all of these methods, you can control which
events are generated:
>>> class ParserTarget:… events = []… close_count = 0… def start(self, tag, attrib):… ((“start”, tag, attrib))… def close(self):… events, =, []… ose_count += 1… return events
>>> parser_target = ParserTarget()
>>> parser = etree. XMLParser(target=parser_target)
>>> events = omstring(‘‘, parser)
>>> print(ose_count)
>>> for event in events:… print(‘event:%s – tag:%s’% (event[0], event[1]))… for attr, value in event[2]():… print(‘ *%s =%s’% (attr, value))
event: start – tag: root
* test = true
You can reuse the parser and its target as often as you like, so you
should take care that the () method really resets the
target to a usable state (also in the case of an error! ).
2
4
The ElementTree API avoids
namespace prefixes
wherever possible and deploys the real namespace (the URI) instead:
>>> xhtml = etree. Element(“{html”)
>>> body = bElement(xhtml, “{body”)
>>> = “Hello World”
>>> print(string(xhtml, pretty_print=True))
Hello World
>>> print((“bgcolor”))
>>> (XHTML + “bgcolor”)
‘#CCFFAA’
You can also use XPath with fully qualified names:
>>> find_xhtml_body = XPath( # lxml only!… “//{%s}body”% XHTML_NAMESPACE)
>>> results = find_xhtml_body(xhtml)
>>> print(results[0])
{body
For convenience, you can use “*” wildcards in all iterators of,
both for tag names and namespaces:
>>> for el in (‘*’): print() # any element
>>> for el in (‘{*’): print()
>>> for el in (‘{*}body’): print()
To look for elements that do not have a namespace, either use the
plain tag name or provide the empty namespace explicitly:
>>> [ for el in (‘{body’)]
[‘{body’]
>>> [ for el in (‘body’)]
[]
>>> [ for el in (‘{}body’)]
>>> [ for el in (‘{}*’)]
The E-factory provides a simple and compact syntax for generating XML and
HTML:
>>> from er import E
>>> def CLASS(*args): # class is a reserved word in Python… return {“class”:’ ‘(args)}
>>> html = page = (… ( # create an Element called “html”… (… (“This is a sample document”)… ),… E. h1(“Hello! “, CLASS(“title”)),… p(“This is a paragraph with “, E. b(“bold”), ” text in it! “),… p(“This is another paragraph, with a”, “n “,… a(“link”, href=”), “. “),… p(“Here are some reserved characters: . (“

And finally an embedded XHTML fragment.

“),… )… )
>>> print(string(page, pretty_print=True))

This is a sample document

Hello!

This is a paragraph with bold text in it!

This is another paragraph, with a
The dog and the hog The dog Once upon a time,… And then… The hog Sooner or later… One such example is the module, which provides a
vocabulary for HTML.
When dealing with multiple namespaces, it is good practice to define
one ElementMaker for each namespace URI. Again, note how the above
example predefines the tag builders in named constants. That makes it
easy to put all tag declarations of a namespace into one Python module
and to import/use the tag name constants from there. This avoids
pitfalls like typos or accidentally missing namespaces.
The ElementTree library comes with a simple XPath-like path language
called ElementPath. The main difference is that you can use the
{namespace}tag notation in ElementPath expressions. However,
advanced features like value comparison and functions are not
available.
In addition to a full XPath implementation, supports the
ElementPath language in the same way ElementTree does, even using
(almost) the same implementation. The API provides four methods here
that you can find on Elements and ElementTrees:
iterfind() iterates over all Elements that match the path
expression
findall() returns a list of matching Elements
find() efficiently returns only the first match
findtext() returns the content of the first match
Here are some examples:
>>> root = (“
aText“)
Find a child of an Element:
>>> print((“b”))
>>> print((“a”))
a
Find an Element anywhere in the tree:
>>> print((“. //b”))
b
>>> [ for b in erfind(“. //b”)]
[‘b’, ‘b’]
Find Elements with a certain attribute:
>>> print(ndall(“. //a[@x]”)[0])
>>> print(ndall(“. //a[@y]”))
In lxml 3. 4, there is a new helper to generate a structural ElementPath
expression for an Element:
>>> a = root[0]
>>> print(telementpath(a[0]))
a/b[1]
>>> print(telementpath(a[1]))
a/c
>>> print(telementpath(a[2]))
a/b[2]
>>> (telementpath(a[2])) == a[2]
As long as the tree is not modified, this path expression represents an
identifier for a given element that can be used to find() it in the same
tree later. Compared to XPath, ElementPath expressions have the advantage
of being self-contained even for documents that use namespaces.
The () method is a special case that only finds specific tags
in the tree by their name, not based on a path. That means that the
following commands are equivalent in the success case:
>>> print(next(erfind(“. //b”)))
>>> print(next((“b”)))
Note that the () method simply returns None if no match is found,
whereas the other two examples would raise a StopIteration exception.
lxml.etree

lxml.etree

AncestorsIterator
AncestorsIterator(self, node, tag=None)
Iterates over the ancestors of an element (from parent to parent).
AttributeBasedElementClassLookup
AttributeBasedElementClassLookup(self, attribute_name, class_mapping, fallback=None)
Checks an attribute of an Element and looks up the value in a
class dictionary.
C14NError
Error during C14N serialisation.
C14NWriterTarget
Canonicalization writer target for the XMLParser.
CDATA
CDATA(data)
CommentBase
All custom Comment classes must inherit from this one.
CustomElementClassLookup
CustomElementClassLookup(self, fallback=None)
Element class lookup based on a subclass method.
DTD
DTD(self, file=None, external_id=None)
A DTD validator.
DTDError
Base class for DTD errors.
DTDParseError
Error while parsing a DTD.
DTDValidateError
Error while validating an XML document with a DTD.
DocInfo
Document information provided by parser and DTD.
DocumentInvalid
Validation error.
ETCompatXMLParser
ETCompatXMLParser(self, encoding=None, attribute_defaults=False, dtd_validation=False, load_dtd=False, no_network=True, ns_clean=False, recover=False, schema=None, huge_tree=False, remove_blank_text=False, resolve_entities=True, remove_comments=True, remove_pis=True, strip_cdata=True, target=None, compact=True)
ETXPath
ETXPath(self, path, extensions=None, regexp=True, smart_strings=True)
Special XPath class that supports the ElementTree {uri} notation for namespaces.
ElementBase
ElementBase(*children, attrib=None, nsmap=None, **_extra)
ElementChildIterator
ElementChildIterator(self, node, tag=None, reversed=False)
Iterates over the children of an element.
ElementClassLookup
ElementClassLookup(self)
Superclass of Element class lookups.
ElementDefaultClassLookup
ElementDefaultClassLookup(self, element=None, comment=None, pi=None, entity=None)
Element class lookup scheme that always returns the default Element
class.
ElementDepthFirstIterator
ElementDepthFirstIterator(self, node, tag=None, inclusive=True)
Iterates over an element and its sub-elements in document order (depth
first pre-order).
ElementNamespaceClassLookup
ElementNamespaceClassLookup(self, fallback=None)
ElementTextIterator
ElementTextIterator(self, element, tag=None, with_tail=True)
Iterates over the text content of a subtree.
EntityBase
All custom Entity classes must inherit from this one.
Error
ErrorDomains
Libxml2 error domains
ErrorLevels
Libxml2 error levels
ErrorTypes
Libxml2 error types
FallbackElementClassLookup
FallbackElementClassLookup(self, fallback=None)
HTMLParser
HTMLParser(self, encoding=None, remove_blank_text=False, remove_comments=False, remove_pis=False, strip_cdata=True, no_network=True, target=None, schema: XMLSchema =None, recover=True, compact=True, collect_ids=True, huge_tree=False)
HTMLPullParser
HTMLPullParser(self, events=None, *, tag=None, base_url=None, **kwargs)
LxmlError
Main exception base class for lxml. All other exceptions inherit from
this one.
LxmlRegistryError
Base class of lxml registry errors.
LxmlSyntaxError
Base class for all syntax errors.
NamespaceRegistryError
Error registering a namespace extension.
PIBase
All custom Processing Instruction classes must inherit from this one.
ParseError
Syntax error while parsing an XML document.
ParserBasedElementClassLookup
ParserBasedElementClassLookup(self, fallback=None)
Element class lookup based on the XML parser.
ParserError
Internal lxml parser error.
PyErrorLog
PyErrorLog(self, logger_name=None, logger=None)
A global error log that connects to the Python stdlib logging package.
PythonElementClassLookup
PythonElementClassLookup(self, fallback=None)
QName
QName(text_or_uri_or_element, tag=None)
RelaxNG
RelaxNG(self, etree=None, file=None)
Turn a document into a Relax NG validator.
RelaxNGError
Base class for RelaxNG errors.
RelaxNGErrorTypes
Libxml2 RelaxNG error types
RelaxNGParseError
Error while parsing an XML document as RelaxNG.
RelaxNGValidateError
Error while validating an XML document with a RelaxNG schema.
Resolver
This is the base class of all resolvers.
Schematron
Schematron(self, etree=None, file=None)
A Schematron validator.
SchematronError
Base class of all Schematron errors.
SchematronParseError
Error while parsing an XML document as Schematron schema.
SchematronValidateError
Error while validating an XML document with a Schematron schema.
SerialisationError
A libxml2 error that occurred during serialisation.
SiblingsIterator
SiblingsIterator(self, node, tag=None, preceding=False)
Iterates over the siblings of an element.
TreeBuilder
comment_factory=None, pi_factory=None,
insert_comments=True, insert_pis=True)
XInclude
XInclude(self)
XInclude processor.
XIncludeError
Error during XInclude processing.
XMLParser
XMLParser(self, encoding=None, attribute_defaults=False, dtd_validation=False, load_dtd=False, no_network=True, ns_clean=False, recover=False, schema: XMLSchema =None, huge_tree=False, remove_blank_text=False, resolve_entities=True, remove_comments=False, remove_pis=False, strip_cdata=True, collect_ids=True, target=None, compact=True)
XMLPullParser
XMLPullParser(self, events=None, *, tag=None, **kwargs)
XMLSchema
XMLSchema(self, etree=None, file=None)
Turn a document into an XML Schema validator.
XMLSchemaError
Base class of all XML Schema errors
XMLSchemaParseError
Error while parsing an XML document as XML Schema.
XMLSchemaValidateError
Error while validating an XML document with an XML Schema.
XMLSyntaxError
XMLTreeBuilder
XPath
XPath(self, path, namespaces=None, extensions=None, regexp=True, smart_strings=True)
A compiled XPath expression that can be called on Elements and ElementTrees.
XPathDocumentEvaluator
XPathDocumentEvaluator(self, etree, namespaces=None, extensions=None, regexp=True, smart_strings=True)
Create an XPath evaluator for an ElementTree.
XPathElementEvaluator
XPathElementEvaluator(self, element, namespaces=None, extensions=None, regexp=True, smart_strings=True)
Create an XPath evaluator for an element.
XPathError
Base class of all XPath errors.
XPathEvalError
Error during XPath evaluation.
XPathFunctionError
Internal error looking up an XPath extension function.
XPathResultError
Error handling an XPath result.
XPathSyntaxError
XSLT
XSLT(self, xslt_input, extensions=None, regexp=True, access_control=None)
XSLTAccessControl
XSLTAccessControl(self, read_file=True, write_file=True, create_dir=True, read_network=True, write_network=True)
XSLTApplyError
Error running an XSL transformation.
XSLTError
Base class of all XSLT errors.
XSLTExtension
Base class of an XSLT extension element.
XSLTExtensionError
Error registering an XSLT extension.
XSLTParseError
Error parsing a stylesheet document.
XSLTSaveError
Error serialising an XSLT result.
_Attrib
A dict-like proxy for the property.
_BaseErrorLog
_Comment
_Document
Internal base class to reference a libxml document.
_DomainErrorLog
_Element
Element class.
_ElementIterator
Dead but public. 🙂
_ElementMatchIterator
_ElementStringResult
_ElementTagMatcher
_ElementTree
_ElementUnicodeResult
_Entity
_ErrorLog
_FeedParser
_IDDict
IDDict(self, etree)
A dictionary-like proxy class that mapps ID attributes to elements.
_ListErrorLog
Immutable base version of a list based error log.
_LogEntry
A log message entry from an error log.
_ProcessingInstruction
_RotatingErrorLog
_SaxParserTarget
_TargetParserResult
_Validator
Base class for XML validators.
_XPathEvaluatorBase
_XSLTProcessingInstruction
_XSLTResultTree
The result of an XSLT evaluation.
htmlfile
htmlfile(self, output_file, encoding=None, compression=None, close=False, buffered=True)
iterparse
iterparse(self, source, events=(“end”, ), tag=None, attribute_defaults=False, dtd_validation=False, load_dtd=False, no_network=True, remove_blank_text=False, remove_comments=False, remove_pis=False, encoding=None, html=False, recover=None, huge_tree=False, schema=None)
iterwalk
iterwalk(self, element_or_tree, events=(“end”, ), tag=None)
xmlfile
xmlfile(self, output_file, encoding=None, compression=None, close=False, buffered=True)
Comment(text=None)
Comment element factory. This factory function creates a special element that will
be serialized as an XML comment.
Element(_tag,
attrib=None,
nsmap=None,
**_extra)
Element factory. This function returns an object implementing the
Element interface.
ElementTree(element=None,
file=None,
parser=None)
ElementTree wrapper class.
Entity(name)
Entity factory. This factory function creates a special element
that will be serialized as an XML entity reference or character
reference. Note, however, that entities will not be automatically
declared in the document. A document that uses entity references
requires a DTD to define the entities.
Extension(module,
function_mapping=None,
ns=None)
Build a dictionary of extension functions from the functions
defined in a module or the methods of an object.
FunctionNamespace(ns_uri)
Retrieve the function namespace object associated with the given
URI.
HTML(text,
parser=None,
base_url=None)
Parses an HTML document from a string constant. Returns the root
node (or the result returned by a parser target). This function
can be used to embed “HTML literals” in Python code.
PI(target,
text=None)
ProcessingInstruction element factory. This factory function creates a
special element that will be serialized as an XML processing instruction.
ProcessingInstruction(target,
SubElement(_parent,
_tag,
Subelement factory. This function creates an element instance, and
appends it to an existing element.
XML(text,
Parses an XML document or fragment from a string constant.
Returns the root node (or the result returned by a parser target).
This function can be used to embed “XML literals” in Python code,
like in
XMLDTDID(text,
Parse the text and return a tuple (root node, ID dictionary). The root
node is the same as returned by the XML() function. The dictionary
contains string-element pairs. The dictionary keys are the values of ID
attributes as defined by the DTD. The elements referenced by the ID are
stored as dictionary values.
XMLID(text,
contains string-element pairs. The dictionary keys are the values of ‘id’
attributes. The elements referenced by the ID are stored as dictionary
values.
XPathEvaluator(etree_or_element,
namespaces=None,
extensions=None,
regexp=True,
smart_strings=True)
Creates an XPath evaluator for an ElementTree or an Element.
adopt_external_document(capsule,
Unpack a libxml2 document pointer from a PyCapsule and wrap it in an
lxml ElementTree object.
canonicalize(… )
Convert XML to its C14N 2. 0 serialised form.
cleanup_namespaces(tree_or_element,
top_nsmap=None,
keep_ns_prefixes=None)
Remove all namespace declarations from a subtree that are not used
by any of the elements or attributes in that tree.
clear_error_log()
Clear the global error log. Note that this log is already bound to a
fixed size.
dump(elem,
pretty_print=True,
with_tail=True)
Writes an element tree or element structure to This function
should be used for debugging only.
fromstring(text,
Parses an XML document or fragment from a string. Returns the
root node (or the result returned by a parser target).
fromstringlist(strings,
Parses an XML document from a sequence of strings. Returns the
indent(tree,
space=” “,
level=0)
Indent an XML document by inserting newlines and indentation space
after elements.
iselement(element)
Checks if an object appears to be a valid element object.
parse(source,
Return an ElementTree object loaded with source elements. If no parser
is provided as second argument, the default parser is used.
parseid(source,
Parses the source into a tuple containing an ElementTree object and an
ID dictionary. If no parser is provided as second argument, the default
parser is used.
register_namespace(… )
Registers a namespace prefix that newly created Elements in that
namespace will use. The registry is global, and any existing
mapping for either the given prefix or the namespace URI will be
removed.
set_default_parser(parser=None)
Set a default parser for the current thread. This parser is used
globally whenever no parser is supplied to the various parse functions of
the lxml API. If this function is called without a parser (or if it is
None), the default parser is reset to the original configuration.
set_element_class_lookup(lookup= None)
Set the global default element class lookup method.
strip_attributes(tree_or_element,
*attribute_names)
Delete all attributes with the provided attribute names from an
Element (or ElementTree) and its descendants.
strip_elements(tree_or_element,
with_tail=True,
*tag_names)
Delete all elements with the provided tag names from a tree or
subtree. This will remove the elements and their entire subtree,
including all their attributes, text content and descendants. It
will also remove the tail text of the element unless you
explicitly set the with_tail keyword argument option to False.
strip_tags(tree_or_element,
subtree. This will remove the elements and their attributes, but
not their text/tail content or descendants. Instead, it will
merge the text content and children of the element into its
parent.
tostring(element_or_tree,
encoding=None,
method=”xml”,
xml_declaration=None,
pretty_print=False,
standalone=None,
doctype=None,
exclusive=False,
inclusive_ns_prefixes=None,
with_comments=True,
strip_text=False, )
Serialize an element to an encoded string representation of its XML
tree.
tostringlist(element_or_tree,
*args,
**kwargs)
tree, stored in a list of partial strings.
tounicode(element_or_tree,
doctype=None)
Serialize an element to the Python unicode representation of its XML
use_global_python_log(log)
Replace the global error log by an ErrorLog that uses the
standard Python logging package.
DEBUG = 1
LIBXML_COMPILED_VERSION = (2, 9, 4)
LIBXML_VERSION = (2, 9, 4)
LIBXSLT_COMPILED_VERSION = (1, 1, 29)
LIBXSLT_VERSION = (1, 1, 29)
LXML_VERSION = (4, 5, 2, 0)
__package__ = None
hash(x)
__pyx_capi__ = {‘adoptExternalDocument’:
Defaults to ASCII encoding without XML declaration. This
behaviour can be configured with the keyword arguments ‘encoding’
(string) and ‘xml_declaration’ (bool). Note that changing the
encoding to a non UTF-8 compatible encoding will enable a
declaration by default.
You can also serialise to a Unicode string without declaration by
passing the name ‘unicode’ as encoding (or the str function
in Py3 or unicode in Py2). This changes the return value from
a byte string to an unencoded unicode string.
The keyword argument ‘pretty_print’ (bool) enables formatted XML.
The keyword argument ‘method’ selects the output method: ‘xml’,
‘html’, plain ‘text’ (text content without tags), ‘c14n’ or ‘c14n2’.
Default is ‘xml’.
With method=”c14n” (C14N version 1), the options exclusive,
with_comments and inclusive_ns_prefixes request exclusive
C14N, include comments, and list the inclusive prefixes respectively.
With method=”c14n2″ (C14N version 2), the with_comments and
strip_text options control the output of comments and text space
according to C14N 2. 0.
Passing a boolean value to the standalone option will output
an XML declaration with the corresponding standalone flag.
The doctype option allows passing in a plain string that will
be serialised before the XML tree. Note that passing in non
well-formed content here will make the XML output non well-formed.
Also, an existing doctype in the document tree will not be removed
when serialising an ElementTree instance.
You can prevent the tail text of the element from being serialised
by passing the boolean with_tail option. This has no impact
on the tail text of children, which will always be serialised.
The lxml.etree Tutorial

The lxml.etree Tutorial

Author:
Stefan Behnel
This tutorial briefly overviews the main concepts of the ElementTree API as
implemented by, and some simple enhancements that make your
life as a programmer easier.
For a complete reference of the API, see the generated API
documentation.
Contents
The Element class
Elements are lists
Elements carry attributes
Elements contain text
Using XPath to find text
Tree iteration
Serialisation
The ElementTree class
Parsing from strings and files
The fromstring() function
The XML() function
The parse() function
Parser objects
Incremental parsing
Event-driven parsing
Namespaces
The E-factory
ElementPath
A common way to import is as follows:
>>> from lxml import etree
If your code only uses the ElementTree API and does not rely on any
functionality that is specific to, you can also use (any part
of) the following import chain as a fall-back to the original ElementTree:
try:
from lxml import etree
print(“running with “)
except ImportError:
# Python 2. 5
import as etree
print(“running with cElementTree on Python 2. 5+”)
print(“running with ElementTree on Python 2. 5+”)
# normal cElementTree install
import cElementTree as etree
print(“running with cElementTree”)
# normal ElementTree install
import elementtree. ElementTree as etree
print(“running with ElementTree”)
print(“Failed to import ElementTree from any known place”)
To aid in writing portable code, this tutorial makes it clear in the examples
which part of the presented API is an extension of over the
original ElementTree API, as defined by Fredrik Lundh’s ElementTree
library.
An Element is the main container object for the ElementTree API. Most of
the XML tree functionality is accessed through this class. Elements are
easily created through the Element factory:
>>> root = etree. Element(“root”)
The XML tag name of elements is accessed through the tag property:
Elements are organised in an XML tree structure. To create child elements and
add them to a parent element, you can use the append() method:
>>> ( etree. Element(“child1”))
However, this is so common that there is a shorter and much more efficient way
to do this: the SubElement factory. It accepts the same arguments as the
Element factory, but additionally requires the parent as first argument:
>>> child2 = bElement(root, “child2”)
>>> child3 = bElement(root, “child3”)
To see that this is really XML, you can serialise the tree you have created:
>>> print(string(root, pretty_print=True))





To make the access to these subelements as easy and straight forward as
possible, elements behave like normal Python lists:
>>> child = root[0]
>>> print()
child1
>>> print(len(root))
3
>>> (root[1]) # only!
1
>>> children = list(root)
>>> for child in root:… print()
child2
child3
>>> (0, etree. Element(“child0”))
>>> start = root[:1]
>>> end = root[-1:]
>>> print(start[0])
child0
>>> print(end[0])
>>> root[0] = root[-1] # this moves the element!
Prior to ElementTree 1. 3 and lxml 2. 0, you could also check the truth value of
an Element to see if it has children, i. e. if the list of children is empty.
This is no longer supported as people tend to find it surprising that a
non-None reference to an existing Element can evaluate to False. Instead, use
len(element), which is both more explicit and less error prone.
Note in the examples that the last element was moved to a different position
in the last example. This is a difference from the original ElementTree (and
from lists), where elements can sit in multiple positions of any number of
trees. In, elements can only sit in one position of one tree at a
time.
If you want to copy an element to a different position, consider creating an
independent deep copy using the copy module from Python’s standard
library:
>>> from copy import deepcopy
>>> element = etree. Element(“neu”)
>>> ( deepcopy(root[1]))
>>> print(element[0])
>>> print([ for c in root])
[‘child3’, ‘child1’, ‘child2′]
The way up in the tree is provided through the getparent() method:
>>> root is root[0]. getparent() # only!
True
The siblings (or neighbours) of an element are accessed as next and previous
elements:
>>> root[0] is root[1]. getprevious() # only!
>>> root[1] is root[0]. getnext() # only!
XML elements support attributes. You can create them directly in the Element
factory:
>>> root = etree. Element(“root”, interesting=”totally”)
>>> string(root)
b’
Fast and direct access to these attributes is provided by the set() and
get() methods of elements:
>>> print((“interesting”))
totally
>>> (“interesting”, “somewhat”)
somewhat
However, a very convenient way of dealing with them is through the dictionary
interface of the attrib property:
>>> attributes =
>>> print(attributes[“interesting”])
>>> print((“hello”))
None
>>> attributes[“hello”] = “Guten Tag”
Guten Tag
Elements can contain text:
>>> = “TEXT”
TEXT
b’TEXT
In many XML documents (data-centric documents), this is the only place where
text can be found. It is encapsulated by a leaf tag at the very bottom of the
tree hierarchy.
However, if XML is used for tagged text documents such as (X)HTML, text can
also appear between different elements, right in the middle of the tree:
Hello
World
Here, the
tag is surrounded by text. This is often referred to as
document-style or mixed-content XML. Elements support this through their
tail property. It contains the text that directly follows the element, up
to the next element in the XML tree:
>>> html = etree. Element(“html”)
>>> body = bElement(html, “body”)
>>> string(html)
b’TEXT‘
>>> br = bElement(body, “br”)
b’TEXT

>>> = “TAIL”
b’TEXT
TAIL‘
The two properties and are enough to represent any
text content in an XML document. This way, the ElementTree API does
not require any special text nodes in addition to the Element
class, that tend to get in the way fairly often (as you might know
from classic DOM APIs).
However, there are cases where the tail text also gets in the way.
For example, when you serialise an Element from within the tree, you
do not always want its tail text in the result (although you would
still want the tail text of its children). For this purpose, the
tostring() function accepts the keyword argument with_tail:
>>> string(br)
b’
TAIL’
>>> string(br, with_tail=False) # only!
b’

If you want to read only the text, i. without any intermediate
tags, you have to recursively concatenate all text and tail
attributes in the correct order. Again, the tostring() function
comes to the rescue, this time using the method keyword:
>>> string(html, method=”text”)
b’TEXTTAIL’
Another way to extract the text content of a tree is XPath, which
also allows you to extract the separate text chunks into a list:
>>> print((“string()”)) # only!
TEXTTAIL
>>> print((“//text()”)) # only!
[‘TEXT’, ‘TAIL’]
If you want to use this more often, you can wrap it in a function:
>>> build_text_list = (“//text()”) # only!
>>> print(build_text_list(html))
Note that a string result returned by XPath is a special ‘smart’
object that knows about its origins. You can ask it where it came
from through its getparent() method, just as you would with
Elements:
>>> texts = build_text_list(html)
>>> print(texts[0])
>>> parent = texts[0]. getparent()
body
>>> print(texts[1])
TAIL
>>> print(texts[1]. getparent())
br
You can also find out if it’s normal text content or tail text:
>>> print(texts[0]. is_text)
>>> print(texts[1]. is_text)
False
>>> print(texts[1]. is_tail)
While this works for the results of the text() function, lxml will
not tell you the origin of a string value that was constructed by the
XPath functions string() or concat():
>>> stringify = (“string()”)
>>> print(stringify(html))
>>> print(stringify(html). getparent())
For problems like the above, where you want to recursively traverse the tree
and do something with its elements, tree iteration is a very convenient
solution. Elements provide a tree iterator for this purpose. It yields
elements in document order, i. in the order their tags would appear if you
serialised the tree to XML:
>>> bElement(root, “child”) = “Child 1”
>>> bElement(root, “child”) = “Child 2”
>>> bElement(root, “another”) = “Child 3”
Child 1
Child 2
Child 3
>>> for element in ():… print(“%s -%s”% (, ))
root – None
child – Child 1
child – Child 2
another – Child 3
If you know you are only interested in a single tag, you can pass its name to
iter() to have it filter for you:
>>> for element in (“child”):… print(“%s -%s”% (, ))
By default, iteration yields all nodes in the tree, including
ProcessingInstructions, Comments and Entity instances. If you want to
make sure only Element objects are returned, you can pass the
Element factory as tag parameter:
>>> ((“#234”))
>>> (mment(“some comment”))
>>> for element in ():… if isinstance(, basestring):… print(“%s -%s”% (, ))… else:… print(“SPECIAL:%s -%s”% (element, ))
SPECIAL: ê – ê
SPECIAL: – some comment
>>> for element in (tag=etree. Element):… print(“%s -%s”% (, ))
>>> for element in ():… print()
ê
In, elements provide further iterators for all directions in the
tree: children, parents (or rather ancestors) and siblings.
Serialisation commonly uses the tostring() function that returns a
string, or the () method that writes to a file or
file-like object. Both accept the same keyword arguments like
pretty_print for formatted output or encoding to select a
specific output encoding other than plain ASCII:
>>> root = (‘‘)
b’
>>> print(string(root, xml_declaration=True))


>>> print(string(root, encoding=’iso-8859-1′))




Note that pretty printing appends a newline at the end.
Since lxml 2. 0 (and ElementTree 1. 3), the serialisation functions can
do more than XML serialisation. You can serialise to HTML or extract
the text content by passing the method keyword:
>>> root = (… ‘

Hello
World

‘)
>>> string(root) # default: method = ‘xml’
b’

Hello
World


>>> string(root, method=’xml’) # same as above
>>> string(root, method=’html’)
b’

Hello
World


>>> print(string(root, method=’html’, pretty_print=True))


Hello
World



>>> string(root, method=’text’)
b’HelloWorld’
As for XML serialisation, the default encoding for plain text
serialisation is ASCII:
>>> br = (‘. //br’)
>>> = u’Wxf6rld’
>>> string(root, method=’text’) # doctest: +ELLIPSIS
Traceback (most recent call last):…
UnicodeEncodeError: ‘ascii’ codec can’t encode character u’xf6’…
>>> string(root, method=’text’, encoding=”UTF-8″)
b’HelloWxc3xb6rld’
Here, serialising to a Python unicode string instead of a byte string
might become handy. Just pass the unicode type as encoding:
>>> string(root, encoding=unicode, method=’text’)
u’HelloWxf6rld’
An ElementTree is mainly a document wrapper around a tree with a
root node. It provides a couple of methods for parsing, serialisation
and general document handling. One of the bigger differences is that
it serialises as a complete document, as opposed to a single
Element. This includes top-level processing instructions and
comments, as well as a DOCTYPE and other DTD content in the document:
>>> tree = (StringIO(”’… ]>… &tasty;… ”’))
>>> print(ctype)

>>> # lxml 1. 3. 4 and later
>>> print(string(tree))
]>
eggs
>>> print(string(etree. ElementTree(troot())))
>>> # ElementTree and lxml <= 1. 3 >>> print(string(troot()))
Note that this has changed in lxml 1. 4 to match the behaviour of
lxml 2. 0. Before, the examples were serialised without DTD content,
which made lxml loose DTD information in an input-output cycle.
supports parsing XML in a number of ways and from all
important sources, namely strings, files, URLs (/ftp) and
file-like objects. The main parse functions are fromstring() and
parse(), both called with the source as first argument. By
default, they use the standard parser, but you can always pass a
different parser as second argument.
The fromstring() function is the easiest way to parse a string:
>>> some_xml_data = “data
>>> root = omstring(some_xml_data)
root
b’data
The XML() function behaves like the fromstring() function, but is
commonly used to write XML literals right into the source:
>>> root = (“data“)
The parse() function is used to parse from files and file-like objects:
>>> some_file_like = StringIO(“data“)
>>> tree = (some_file_like)
>>> string(tree)
Note that parse() returns an ElementTree object, not an Element object as
the string parser functions:
>>> root = troot()
The reasoning behind this difference is that parse() returns a
complete document from a file, while the string parsing functions are
commonly used to parse XML fragments.
The parse() function supports any of the following sources:
an open file object
a file-like object that has a (byte_count) method returning
a byte string on each call
a filename string
an HTTP or FTP URL string
Note that passing a filename or URL is usually faster than passing an
open file.
By default, uses a standard parser with a default setup. If
you want to configure the parser, you can create a you instance:
>>> parser = etree. XMLParser(remove_blank_text=True) # only!
This creates a parser that removes empty text between tags while parsing,
which can reduce the size of the tree and avoid dangling tail text if you know
that whitespace-only content is not meaningful for your data. An example:
>>> root = (“ “, parser)
b’

Note that the whitespace content inside the tag was not removed, as
content at leaf elements tends to be data content (even if blank). You can
easily remove it in an additional step by traversing the tree:
>>> for element in (“*”):… if is not None and not ():… = None
b’

See help(etree. XMLParser) to find out about the available parser options.
provides two ways for incremental step-by-step parsing. One is
through file-like objects, where it calls the read() method repeatedly.
This is best used where the data arrives from a source like urllib or any
other file-like object that can provide data on request. Note that the parser
will block and wait until data becomes available in this case:
>>> class DataSource:… data = [ b”<", b"a/", b"><", b"/root>“]… def read(self, requested_size):… try:… return (0)… except IndexError:… return b”
>>> tree = (DataSource())
b’

The second way is through a feed parser interface, given by the feed(data)
and close() methods:
>>> parser = etree. XMLParser()
>>> (“>> (“t><") >>> (“a/”)
>>> (“><") >>> (“/root>”)
>>> root = ()
Here, you can interrupt the parsing process at any time and continue it later
on with another call to the feed() method. This comes in handy if you
want to avoid blocking calls to the parser, e. g. in frameworks like Twisted,
or whenever data comes in slowly or in chunks and you want to do other things
while waiting for the next chunk.
After calling the close() method (or when an exception was raised
by the parser), you can reuse the parser by calling its feed()
method again:
>>> (““)
b’
Sometimes, all you need from a document is a small fraction somewhere deep
inside the tree, so parsing the whole tree into memory, traversing it and
dropping it can be too much overhead. supports this use case
with two event-driven parser interfaces, one that generates parser events
while building the tree (iterparse), and one that does not build the tree
at all, and instead calls feedback methods on a target object in a SAX-like
fashion.
Here is a simple iterparse() example:
>>> some_file_like = StringIO(“
data“)
>>> for event, element in erparse(some_file_like):… print(“%s, %4s, %s”% (event,, ))
end, a, data
end, root, None
By default, iterparse() only generates events when it is done parsing an
element, but you can control this through the events keyword argument:
>>> for event, element in erparse(some_file_like,… events=(“start”, “end”)):… print(“%5s, %4s, %s”% (event,, ))
start, root, None
start, a, data
Note that the text, tail and children of an Element are not necessarily there
yet when receiving the start event. Only the end event guarantees
that the Element has been parsed completely.
It also allows to () or modify the content of an Element to
save memory. So if you parse a large tree and you want to keep memory
usage small, you should clean up parts of the tree that you no longer
need:
>>> some_file_like = StringIO(… “data“)
>>> for event, element in erparse(some_file_like):… if == ‘b’:… print()… elif == ‘a’:… print(“** cleaning up the subtree”)… ()
data
** cleaning up the subtree
If memory is a real bottleneck, or if building the tree is not desired at all,
the target parser interface of can be used. It creates
SAX-like events by calling the methods of a target object. By implementing
some or all of these methods, you can control which events are generated:
>>> class ParserTarget:… events = []… def start(self, tag, attrib):… ((“start”, tag, attrib))… def close(self):… return
>>> parser = etree. XMLParser(target=ParserTarget())
>>> events = omstring(‘‘, parser)
>>> for event in events:… print(‘event:%s – tag:%s’% (event[0], event[1]))… for attr, value in event[2]():… print(‘ *%s =%s’% (attr, value))
event: start – tag: root
* test = true
The ElementTree API avoids namespace prefixes wherever possible and deploys
the real namespaces instead:
>>> xhtml = etree. Element(“{html”)
>>> body = bElement(xhtml, “{body”)
>>> = “Hello World”
>>> print(string(xhtml, pretty_print=True))
Hello World
>>> print((“bgcolor”))
>>> (XHTML + “bgcolor”)
‘#CCFFAA’
You can also use XPath in this way:
>>> find_xhtml_body = XPath( # lxml only!… “//{%s}body”% XHTML_NAMESPACE)
>>> results = find_xhtml_body(xhtml)
>>> print(results[0])
{body
The E-factory provides a simple and compact syntax for generating XML and
HTML:
>>> from er import E
>>> def CLASS(*args): # class is a reserved word in Python… return {“class”:’ ‘(args)}
>>> html = page = (… ( # create an Element called “html”… (… (“This is a sample document”)… ),… E. h1(“Hello! “, CLASS(“title”)),… p(“This is a paragraph with “, E. b(“bold”), ” text in it! “),… p(“This is another paragraph, with a”, “n “,… a(“link”, href=”), “. “),… p(“Here are some reservered characters: . (“

And finally an embedded XHTML fragment.

“),… )… )
>>> print(string(page, pretty_print=True))

This is a sample document

Hello!

This is a paragraph with bold text in it!

This is another paragraph, with a
The dog and the hog The dog Once upon a time,… And then… The hog Sooner or later… One such example is the module, which provides a
vocabulary for HTML.
The ElementTree library comes with a simple XPath-like path language
called ElementPath. The main difference is that you can use the
{namespace}tag notation in ElementPath expressions. However,
advanced features like value comparison and functions are not
available.
In addition to a full XPath implementation, supports the
ElementPath language in the same way ElementTree does, even using
(almost) the same implementation. The API provides four methods here
that you can find on Elements and ElementTrees:
iterfind() iterates over all Elements that match the path
expression
findall() returns a list of matching Elements
find() efficiently returns only the first match
findtext() returns the content of the first match
Here are some examples:
>>> root = (“
aText“)
Find a child of an Element:
>>> print((“b”))
>>> print((“a”))
a
Find an Element anywhere in the tree:
>>> print((“. //b”))
b
>>> [ for b in erfind(“. //b”)]
[‘b’, ‘b’]
Find Elements with a certain attribute:
>>> print(ndall(“. //a[@x]”)[0])
>>> print(ndall(“. //a[@y]”))
[]

Frequently Asked Questions about python lxml etree

What is lxml Etree?

lxml. etree supports parsing XML in a number of ways and from all important sources, namely strings, files, URLs (http/ftp) and file-like objects. The main parse functions are fromstring() and parse(), both called with the source as first argument.

What is lxml module in Python?

lxml is a Python library which allows for easy handling of XML and HTML files, and can also be used for web scraping. There are a lot of off-the-shelf XML parsers out there, but for better results, developers sometimes prefer to write their own XML and HTML parsers.Apr 10, 2019

How do you use Etree in Python?

Add them using Subelement() function and define it’s text attribute.child=xml. Element(“employee”) nm = xml. SubElement(child, “name”) nm. text = student. … import xml. etree. ElementTree as et tree = et. ElementTree(file=’employees.xml’) root = tree. … import xml. etree. ElementTree as et tree = et.Jan 16, 2019

Leave a Reply

Your email address will not be published. Required fields are marked *