The lxml.etree Tutorial (2024)

  • lxml
    • lxml
      • Introduction
      • Support the project
      • Documentation
      • Download
      • Mailing list
      • Bug tracker
      • License
      • Old Versions
      • Legal Notice for Donations
    • Why lxml?
      • Motto
      • Aims
    • Installing lxml
      • Requirements
      • Installation
      • Building lxml from sources
      • Using lxml with python-libxml2
      • MS Windows
      • MacOS-X
    • Benchmarks and Speed
      • General notes
      • How to read the timings
      • Parsing and Serialising
      • The ElementTree API
      • XPath
      • A longer example
      • lxml.objectify
    • ElementTree compatibility of lxml.etree
    • lxml FAQ - Frequently Asked Questions
      • General Questions
      • Installation
      • Contributing
      • Bugs
      • Threading
      • Parsing and Serialisation
      • XPath and Document Traversal
  • Developing with lxml
    • The lxml.etree Tutorial
      • The Element class
      • The ElementTree class
      • Parsing from strings and files
      • Namespaces
      • The E-factory
      • ElementPath
    • API reference
    • APIs specific to lxml.etree
      • lxml.etree
      • Other Element APIs
      • Trees and Documents
      • Iteration
      • Error handling on exceptions
      • Error logging
      • Serialisation
      • Incremental XML generation
      • CDATA
      • XInclude and ElementInclude
      • write_c14n on ElementTree
    • Parsing XML and HTML with lxml
      • Parsers
      • The target parser interface
      • The feed parser interface
      • iterparse and iterwalk
      • Python unicode strings
    • Validation with lxml
      • Validation at parse time
      • DTD
      • RelaxNG
      • XMLSchema
      • Schematron
      • (Pre-ISO-Schematron)
    • XPath and XSLT with lxml
      • XPath
      • XSLT
    • lxml.objectify
      • The lxml.objectify API
      • Asserting a Schema
      • ObjectPath
      • Python data types
      • How data types are matched
      • What is different from lxml.etree?
    • lxml.html
      • Parsing HTML
      • HTML Element Methods
      • Running HTML doctests
      • Creating HTML with the E-factory
      • Working with links
      • Forms
      • Cleaning up HTML
      • HTML Diff
      • Examples
    • lxml.cssselect
      • The CSSSelector class
      • The cssselect method
      • Supported Selectors
      • Namespaces
    • BeautifulSoup Parser
      • Parsing with the soupparser
      • Entity handling
      • Using soupparser as a fallback
      • Using only the encoding detection
    • html5lib Parser
      • Differences to regular HTML parsing
      • Function Reference
  • Extending lxml
    • Document loading and URL resolving
      • XML Catalogs
      • URI Resolvers
      • Document loading in context
      • I/O access control in XSLT
    • Python extensions for XPath and XSLT
      • XPath Extension functions
      • XSLT extension elements
    • Using custom Element classes in lxml
      • Background on Element proxies
      • Element initialization
      • Setting up a class lookup scheme
      • Generating XML with custom classes
      • Implementing namespaces
    • Sax support
      • Building a tree from SAX events
      • Producing SAX events from an ElementTree or Element
      • Interfacing with pulldom/minidom
    • The public C-API of lxml.etree
      • Writing external modules in Cython
      • Writing external modules in C
  • Developing lxml
    • How to build lxml from source
      • Cython
      • Github, git and hg
      • Building the sources
      • Running the tests and reporting errors
      • Building an egg
      • Building lxml on MacOS-X
      • Static linking on Windows
      • Building Debian packages from SVN sources
    • How to read the source of lxml
      • What is Cython?
      • Where to start?
      • lxml.etree
      • Python modules
      • lxml.objectify
      • lxml.html
    • Release Changelog
    • Credits
      • Main contributors
      • Special thanks goes to:
  • Sitemap
Author:Stefan Behnel

This is a tutorial on XML processing with lxml.etree. It brieflyoverviews the main concepts of the ElementTree API, and some simpleenhancements that make your life as a programmer easier.

For a complete reference of the API, see the generated APIdocumentation.

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 lxml.etree is as follows:

>>> from lxml import etree

If your code only uses the ElementTree API and does not rely on anyfunctionality that is specific to lxml.etree, you can also use (any partof) the following import chain as a fall-back to the original ElementTree:

try: from lxml import etree print("running with lxml.etree")except ImportError: try: # Python 2.5 import xml.etree.cElementTree as etree print("running with cElementTree on Python 2.5+") except ImportError: try: # Python 2.5 import xml.etree.ElementTree as etree print("running with ElementTree on Python 2.5+") except ImportError: try: # normal cElementTree install import cElementTree as etree print("running with cElementTree") except ImportError: try: # normal ElementTree install import elementtree.ElementTree as etree print("running with ElementTree") except ImportError: print("Failed to import ElementTree from any known place")

To aid in writing portable code, this tutorial makes it clear in the exampleswhich part of the presented API is an extension of lxml.etree over theoriginal ElementTree API, as defined by Fredrik Lundh's ElementTreelibrary.

An Element is the main container object for the ElementTree API. Most ofthe XML tree functionality is accessed through this class. Elements areeasily created through the Element factory:

>>> root = etree.Element("root")

The XML tag name of elements is accessed through the tag property:

>>> print(root.tag)root

Elements are organised in an XML tree structure. To create child elements andadd them to a parent element, you can use the append() method:

>>> root.append( etree.Element("child1") )

However, this is so common that there is a shorter and much more efficient wayto do this: the SubElement factory. It accepts the same arguments as theElement factory, but additionally requires the parent as first argument:

>>> child2 = etree.SubElement(root, "child2")>>> child3 = etree.SubElement(root, "child3")

To see that this is really XML, you can serialise the tree you have created:

>>> print(etree.tostring(root, pretty_print=True))<root> <child1/> <child2/> <child3/></root>

Elements are lists

To make the access to these subelements easy and straight forward,elements mimic the behaviour of normal Python lists as closely aspossible:

>>> child = root[0]>>> print(child.tag)child1>>> print(len(root))3>>> root.index(root[1]) # lxml.etree only!1>>> children = list(root)>>> for child in root:...  print(child.tag)child1child2child3>>> root.insert(0, etree.Element("child0"))>>> start = root[:1]>>> end = root[-1:]>>> print(start[0].tag)child0>>> print(end[0].tag)child3

Prior to ElementTree 1.3 and lxml 2.0, you could also check the truth value ofan 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 havechildren or not. So, many users find it surprising that any Elementwould evaluate to False in an if-statement like the above. Instead,use len(element), which is both more explicit and less error prone.

>>> print(etree.iselement(root)) # test if it's some kind of ElementTrue>>> 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 theoriginal ElementTree (prior to version 1.3 or Python 2.7/3.2):

>>> for child in root:...  print(child.tag)child0child1child2child3>>> root[0] = root[-1] # this moves the element in lxml.etree!>>> for child in root:...  print(child.tag)child3child1child2

In this example, the last element is moved to a different position,instead of being copied, i.e. it is automatically removed from itsprevious position when it is put in a different place. In lists,objects can appear in multiple positions at the same time, and theabove assignment would just copy the item reference into the firstposition, 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 sitin any number of places in any number of trees, which allows for the samecopy operation as with lists. The obvious drawback is that modificationsto 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 lxml.etree alwayshas exactly one parent, which can be queried through the getparent()method. This is not supported in the original ElementTree.

>>> root is root[0].getparent() # lxml.etree only!True

If you want to copy an element to a different position in lxml.etree,consider creating an independent deep copy using the copy modulefrom Python's standard library:

>>> from copy import deepcopy>>> element = etree.Element("neu")>>> element.append( deepcopy(root[1]) )>>> print(element[0].tag)child1>>> print([ c.tag for c in root ])['child3', 'child1', 'child2']

The siblings (or neighbours) of an element are accessed as next and previouselements:

>>> root[0] is root[1].getprevious() # lxml.etree only!True>>> root[1] is root[0].getnext() # lxml.etree only!True

Elements carry attributes as a dict

XML elements support attributes. You can create them directly in the Elementfactory:

>>> root = etree.Element("root", interesting="totally")>>> etree.tostring(root)b'<root interesting="totally"/>'

Attributes are just unordered name-value pairs, so a very convenient wayof dealing with them is through the dictionary-like interface of Elements:

>>> print(root.get("interesting"))totally>>> print(root.get("hello"))None>>> root.set("hello", "Huhu")>>> print(root.get("hello"))Huhu>>> etree.tostring(root)b'<root interesting="totally" hello="Huhu"/>'>>> sorted(root.keys())['hello', 'interesting']>>> for name, value in sorted(root.items()):...  print('%s = %r' % (name, value))hello = 'Huhu'interesting = 'totally'

For the cases where you want to do item lookup or have other reasons forgetting a 'real' dictionary-like object, e.g. for passing it around,you can use the attrib property:

>>> attributes = root.attrib>>> print(attributes["interesting"])totally>>> print(attributes.get("no-such-attribute"))None>>> attributes["hello"] = "Guten Tag">>> print(attributes["hello"])Guten Tag>>> print(root.get("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 attriband vice versa. It also means that the XML tree stays alive in memoryas long as the attrib of one of its Elements is in use. To get anindependent snapshot of the attributes that does not depend on the XMLtree, copy it into a dict:

Elements contain text

Elements can contain text:

>>> root = etree.Element("root")>>> root.text = "TEXT">>> print(root.text)TEXT>>> etree.tostring(root)b'<root>TEXT</root>'

In many XML documents (data-centric documents), this is the only place wheretext can be found. It is encapsulated by a leaf tag at the very bottom of thetree hierarchy.

However, if XML is used for tagged text documents such as (X)HTML, text canalso appear between different elements, right in the middle of the tree:

<html><body>Hello<br/>World</body></html>

Here, the <br/> tag is surrounded by text. This is often referred to asdocument-style or mixed-content XML. Elements support this through theirtail property. It contains the text that directly follows the element, upto the next element in the XML tree:

>>> html = etree.Element("html")>>> body = etree.SubElement(html, "body")>>> body.text = "TEXT">>> etree.tostring(html)b'<html><body>TEXT</body></html>'>>> br = etree.SubElement(body, "br")>>> etree.tostring(html)b'<html><body>TEXT<br/></body></html>'>>> br.tail = "TAIL">>> etree.tostring(html)b'<html><body>TEXT<br/>TAIL</body></html>'

The two properties .text and .tail are enough to represent anytext content in an XML document. This way, the ElementTree API doesnot require any special text nodes in addition to the Elementclass, that tend to get in the way fairly often (as you might knowfrom 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, youdo not always want its tail text in the result (although you wouldstill want the tail text of its children). For this purpose, thetostring() function accepts the keyword argument with_tail:

>>> etree.tostring(br)b'<br/>TAIL'>>> etree.tostring(br, with_tail=False) # lxml.etree only!b'<br/>'

If you want to read only the text, i.e. without any intermediatetags, you have to recursively concatenate all text and tailattributes in the correct order. Again, the tostring() functioncomes to the rescue, this time using the method keyword:

>>> etree.tostring(html, method="text")b'TEXTTAIL'

Using XPath to find text

Another way to extract the text content of a tree is XPath, whichalso allows you to extract the separate text chunks into a list:

>>> print(html.xpath("string()")) # lxml.etree only!TEXTTAIL>>> print(html.xpath("//text()")) # lxml.etree only!['TEXT', 'TAIL']

If you want to use this more often, you can wrap it in a function:

>>> build_text_list = etree.XPath("//text()") # lxml.etree only!>>> print(build_text_list(html))['TEXT', 'TAIL']

Note that a string result returned by XPath is a special 'smart'object that knows about its origins. You can ask it where it camefrom through its getparent() method, just as you would withElements:

>>> texts = build_text_list(html)>>> print(texts[0])TEXT>>> parent = texts[0].getparent()>>> print(parent.tag)body>>> print(texts[1])TAIL>>> print(texts[1].getparent().tag)br

You can also find out if it's normal text content or tail text:

>>> print(texts[0].is_text)True>>> print(texts[1].is_text)False>>> print(texts[1].is_tail)True

While this works for the results of the text() function, lxml willnot tell you the origin of a string value that was constructed by theXPath functions string() or concat():

>>> stringify = etree.XPath("string()")>>> print(stringify(html))TEXTTAIL>>> print(stringify(html).getparent())None

Tree iteration

For problems like the above, where you want to recursively traverse the treeand do something with its elements, tree iteration is a very convenientsolution. Elements provide a tree iterator for this purpose. It yieldselements in document order, i.e. in the order their tags would appear if youserialised the tree to XML:

>>> root = etree.Element("root")>>> etree.SubElement(root, "child").text = "Child 1">>> etree.SubElement(root, "child").text = "Child 2">>> etree.SubElement(root, "another").text = "Child 3">>> print(etree.tostring(root, pretty_print=True))<root> <child>Child 1</child> <child>Child 2</child> <another>Child 3</another></root>>>> for element in root.iter():...  print("%s - %s" % (element.tag, element.text))root - Nonechild - Child 1child - Child 2another - Child 3

If you know you are only interested in a single tag, you can pass its name toiter() to have it filter for you. Starting with lxml 3.0, you can alsopass more than one tag to intercept on multiple tags during iteration.

>>> for element in root.iter("child"):...  print("%s - %s" % (element.tag, element.text))child - Child 1child - Child 2>>> for element in root.iter("another", "child"):...  print("%s - %s" % (element.tag, element.text))child - Child 1child - Child 2another - Child 3

By default, iteration yields all nodes in the tree, includingProcessingInstructions, Comments and Entity instances. If you want tomake sure only Element objects are returned, you can pass theElement factory as tag parameter:

>>> root.append(etree.Entity("#234"))>>> root.append(etree.Comment("some comment"))>>> for element in root.iter():...  if isinstance(element.tag, basestring):...  print("%s - %s" % (element.tag, element.text))...  else:...  print("SPECIAL: %s - %s" % (element, element.text))root - Nonechild - Child 1child - Child 2another - Child 3SPECIAL: &#234; - &#234;SPECIAL: <!--some comment--> - some comment>>> for element in root.iter(tag=etree.Element):...  print("%s - %s" % (element.tag, element.text))root - Nonechild - Child 1child - Child 2another - Child 3>>> for element in root.iter(tag=etree.Entity):...  print(element.text)&#234;

Note that passing a wildcard "*" tag name will also yield allElement nodes (and only elements).

In lxml.etree, elements provide further iterators for all directions in thetree: children, parents (or rather ancestors) and siblings.

Serialisation

Serialisation commonly uses the tostring() function that returns astring, or the ElementTree.write() method that writes to a file, afile-like object, or a URL (via FTP PUT or HTTP POST). Both calls acceptthe same keyword arguments like pretty_print for formatted outputor encoding to select a specific output encoding other than plainASCII:

>>> root = etree.XML('<root><a><b/></a></root>')>>> etree.tostring(root)b'<root><a><b/></a></root>'>>> print(etree.tostring(root, xml_declaration=True))<?xml version='1.0' encoding='ASCII'?><root><a><b/></a></root>>>> print(etree.tostring(root, encoding='iso-8859-1'))<?xml version='1.0' encoding='iso-8859-1'?><root><a><b/></a></root>>>> print(etree.tostring(root, pretty_print=True))<root> <a> <b/> </a></root>

Note that pretty printing appends a newline at the end.

In lxml 2.0 and later (as well as ElementTree 1.3), the serialisationfunctions can do more than XML serialisation. You can serialise toHTML or extract the text content by passing the method keyword:

>>> root = etree.XML(...  '<html><head/><body><p>Hello<br/>World</p></body></html>')>>> etree.tostring(root) # default: method = 'xml'b'<html><head/><body><p>Hello<br/>World</p></body></html>'>>> etree.tostring(root, method='xml') # same as aboveb'<html><head/><body><p>Hello<br/>World</p></body></html>'>>> etree.tostring(root, method='html')b'<html><head></head><body><p>Hello<br>World</p></body></html>'>>> print(etree.tostring(root, method='html', pretty_print=True))<html><head></head><body><p>Hello<br>World</p></body></html>>>> etree.tostring(root, method='text')b'HelloWorld'

As for XML serialisation, the default encoding for plain textserialisation is ASCII:

>>> br = next(root.iter('br')) # get first result of iteration>>> br.tail = u'W\xf6rld'>>> etree.tostring(root, method='text') # doctest: +ELLIPSISTraceback (most recent call last): ...UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' ...>>> etree.tostring(root, method='text', encoding="UTF-8")b'HelloW\xc3\xb6rld'

Here, serialising to a Python unicode string instead of a byte stringmight become handy. Just pass the unicode type as encoding:

>>> etree.tostring(root, encoding=unicode, method='text')u'HelloW\xf6rld'

The W3C has a good article about the Unicode character set andcharacter encodings.

An ElementTree is mainly a document wrapper around a tree with aroot node. It provides a couple of methods for serialisation andgeneral document handling.

>>> root = etree.XML('''\... <?xml version="1.0"?>... <!DOCTYPE root SYSTEM "test" [ <!ENTITY tasty "parsnips"> ]>... <root>...  <a>&tasty;</a>... </root>... ''')>>> tree = etree.ElementTree(root)>>> print(tree.docinfo.xml_version)1.0>>> print(tree.docinfo.doctype)<!DOCTYPE root SYSTEM "test">

An ElementTree is also what you get back when you call theparse() function to parse files or file-like objects (see theparsing section below).

One of the important differences is that the ElementTree classserialises as a complete document, as opposed to a single Element.This includes top-level processing instructions and comments, as wellas a DOCTYPE and other DTD content in the document:

>>> print(etree.tostring(tree)) # lxml 1.3.4 and later<!DOCTYPE root SYSTEM "test" [<!ENTITY tasty "parsnips">]><root> <a>parsnips</a></root>

In the original xml.etree.ElementTree implementation and in lxmlup to 1.3.3, the output looks the same as when serialising onlythe root Element:

>>> print(etree.tostring(tree.getroot()))<root> <a>parsnips</a></root>

This serialisation behaviour has changed in lxml 1.3.4. Before,the tree was serialised without DTD content, which made lxmlloose DTD information in an input-output cycle.

lxml.etree supports parsing XML in a number of ways and from allimportant sources, namely strings, files, URLs (http/ftp) andfile-like objects. The main parse functions are fromstring() andparse(), both called with the source as first argument. Bydefault, they use the standard parser, but you can always pass adifferent parser as second argument.

The fromstring() function

The fromstring() function is the easiest way to parse a string:

>>> some_xml_data = "<root>data</root>">>> root = etree.fromstring(some_xml_data)>>> print(root.tag)root>>> etree.tostring(root)b'<root>data</root>'

The XML() function

The XML() function behaves like the fromstring() function, but iscommonly used to write XML literals right into the source:

>>> root = etree.XML("<root>data</root>")>>> print(root.tag)root>>> etree.tostring(root)b'<root>data</root>'

There is also a corresponding function HTML() for HTML literals.

The parse() function

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 theBytesIO 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 olderPython versions, you will have to use the StringIO class from theStringIO module. However, in real life, you would obviously avoiddoing this all together and use the string parsing functions above.

>>> some_file_like_object = BytesIO("<root>data</root>")>>> tree = etree.parse(some_file_like_object)>>> etree.tostring(tree)b'<root>data</root>'

Note that parse() returns an ElementTree object, not an Element object asthe string parser functions:

>>> root = tree.getroot()>>> print(root.tag)root>>> etree.tostring(root)b'<root>data</root>'

The reasoning behind this difference is that parse() returns acomplete document from a file, while the string parsing functions arecommonly 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 .read(byte_count) method returninga 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 anopen file or file-like object. However, the HTTP/FTP client in libxml2is rather simple, so things like HTTP authentication require a dedicatedURL request library, e.g. urllib2 or request. These librariesusually provide a file-like object for the result that you can parsefrom while the response is streaming in.

Parser objects

By default, lxml.etree uses a standard parser with a default setup. Ifyou want to configure the parser, you can create a you instance:

>>> parser = etree.XMLParser(remove_blank_text=True) # lxml.etree 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 knowthat whitespace-only content is not meaningful for your data. An example:

>>> root = etree.XML("<root> <a/> <b> </b> </root>", parser)>>> etree.tostring(root)b'<root><a/><b> </b></root>'

Note that the whitespace content inside the <b> tag was not removed, ascontent at leaf elements tends to be data content (even if blank). You caneasily remove it in an additional step by traversing the tree:

>>> for element in root.iter("*"):...  if element.text is not None and not element.text.strip():...  element.text = None>>> etree.tostring(root)b'<root><a/><b/></root>'

See help(etree.XMLParser) to find out about the available parser options.

Incremental parsing

lxml.etree provides two ways for incremental step-by-step parsing. One isthrough file-like objects, where it calls the read() method repeatedly.This is best used where the data arrives from a source like urllib or anyother file-like object that can provide data on request. Note that the parserwill block and wait until data becomes available in this case:

>>> class DataSource:...  data = [ b"<roo", b"t><", b"a/", b"><", b"/root>" ]...  def read(self, requested_size):...  try:...  return self.data.pop(0)...  except IndexError:...  return b''>>> tree = etree.parse(DataSource())>>> etree.tostring(tree)b'<root><a/></root>'

The second way is through a feed parser interface, given by the feed(data)and close() methods:

>>> parser = etree.XMLParser()>>> parser.feed("<roo")>>> parser.feed("t><")>>> parser.feed("a/")>>> parser.feed("><")>>> parser.feed("/root>")>>> root = parser.close()>>> etree.tostring(root)b'<root><a/></root>'

Here, you can interrupt the parsing process at any time and continue it lateron with another call to the feed() method. This comes in handy if youwant 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 thingswhile waiting for the next chunk.

After calling the close() method (or when an exception was raisedby the parser), you can reuse the parser by calling its feed()method again:

>>> parser.feed("<root/>")>>> root = parser.close()>>> etree.tostring(root)b'<root/>'

Event-driven parsing

Sometimes, all you need from a document is a small fraction somewhere deepinside the tree, so parsing the whole tree into memory, traversing it anddropping it can be too much overhead. lxml.etree supports this use casewith two event-driven parser interfaces, one that generates parser eventswhile building the tree (iterparse), and one that does not build the treeat all, and instead calls feedback methods on a target object in a SAX-likefashion.

Here is a simple iterparse() example:

>>> some_file_like = BytesIO("<root><a>data</a></root>")>>> for event, element in etree.iterparse(some_file_like):...  print("%s, %4s, %s" % (event, element.tag, element.text))end, a, dataend, root, None

By default, iterparse() only generates events when it is done parsing anelement, but you can control this through the events keyword argument:

>>> some_file_like = BytesIO("<root><a>data</a></root>")>>> for event, element in etree.iterparse(some_file_like,...  events=("start", "end")):...  print("%5s, %4s, %s" % (event, element.tag, element.text))start, root, Nonestart, a, data end, a, data end, root, None

Note that the text, tail and children of an Element are not necessarily thereyet when receiving the start event. Only the end event guaranteesthat the Element has been parsed completely.

It also allows to .clear() or modify the content of an Element tosave memory. So if you parse a large tree and you want to keep memoryusage small, you should clean up parts of the tree that you no longerneed:

>>> some_file_like = BytesIO(...  "<root><a><b>data</b></a><a><b/></a></root>")>>> for event, element in etree.iterparse(some_file_like):...  if element.tag == 'b':...  print(element.text)...  elif element.tag == 'a':...  print("** cleaning up the subtree")...  element.clear()data** cleaning up the subtreeNone** cleaning up the subtree

A very important use cases for iterparse() is parsing largegenerated XML files, e.g. database dumps. Most often, these XMLformats only have one main data item element that hangs directly belowthe root node and that is repeated thousands of times. In this case,it is best practice to let lxml.etree do the tree building and toonly intercept exactly on this one Element, using the normal tree APIfor data extraction.

>>> xml_file = BytesIO('''\... <root>...  <a><b>ABC</b><c>abc</c></a>...  <a><b>MORE DATA</b><c>more data</c></a>...  <a><b>XYZ</b><c>xyz</c></a>... </root>''')>>> for _, element in etree.iterparse(xml_file, tag='a'):...  print('%s -- %s' % (element.findtext('b'), element[1].text))...  element.clear()ABC -- abcMORE DATA -- more dataXYZ -- xyz

If, for some reason, building the tree is not desired at all, thetarget parser interface of lxml.etree can be used. It createsSAX-like events by calling the methods of a target object. Byimplementing some or all of these methods, you can control whichevents are generated:

>>> class ParserTarget:...  events = []...  close_count = 0...  def start(self, tag, attrib):...  self.events.append(("start", tag, attrib))...  def close(self):...  events, self.events = self.events, []...  self.close_count += 1...  return events>>> parser_target = ParserTarget()>>> parser = etree.XMLParser(target=parser_target)>>> events = etree.fromstring('<root test="true"/>', parser)>>> print(parser_target.close_count)1>>> for event in events:...  print('event: %s - tag: %s' % (event[0], event[1]))...  for attr, value in event[2].items():...  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 youshould take care that the .close() methods really resets thetarget to a usable state (also in the case of an error!).

>>> events = etree.fromstring('<root test="true"/>', parser)>>> print(parser_target.close_count)2>>> events = etree.fromstring('<root test="true"/>', parser)>>> print(parser_target.close_count)3>>> events = etree.fromstring('<root test="true"/>', parser)>>> print(parser_target.close_count)4>>> for event in events:...  print('event: %s - tag: %s' % (event[0], event[1]))...  for attr, value in event[2].items():...  print(' * %s = %s' % (attr, value))event: start - tag: root * test = true

The ElementTree API avoidsnamespace prefixeswherever possible and deploys the real namespaces (the URI) instead:

>>> xhtml = etree.Element("{http://www.w3.org/1999/xhtml}html")>>> body = etree.SubElement(xhtml, "{http://www.w3.org/1999/xhtml}body")>>> body.text = "Hello World">>> print(etree.tostring(xhtml, pretty_print=True))<html:html xmlns:html="http://www.w3.org/1999/xhtml"> <html:body>Hello World</html:body></html:html>

The notation that ElementTree uses was originally brought up byJames Clark. It has the majoradvantage of providing a universally qualified name for a tag, regardlessof any prefixes that may or may not have been used or defined in a document.By moving the indirection of prefixes out of the way, it makes namespaceaware code much clearer and easier to get right.

As you can see from the example, prefixes only become important whenyou serialise the result. However, the above code looks somewhatverbose due to the lengthy namespace names. And retyping or copying astring over and over again is error prone. It is therefore commonpractice to store a namespace URI in a global variable. To adapt thenamespace prefixes for serialisation, you can also pass a mapping tothe Element factory function, e.g. to define the default namespace:

>>> XHTML_NAMESPACE = "http://www.w3.org/1999/xhtml">>> XHTML = "{%s}" % XHTML_NAMESPACE>>> NSMAP = {None : XHTML_NAMESPACE} # the default namespace (no prefix)>>> xhtml = etree.Element(XHTML + "html", nsmap=NSMAP) # lxml only!>>> body = etree.SubElement(xhtml, XHTML + "body")>>> body.text = "Hello World">>> print(etree.tostring(xhtml, pretty_print=True))<html xmlns="http://www.w3.org/1999/xhtml"> <body>Hello World</body></html>

You can also use the QName helper class to build or split qualifiedtag names:

>>> tag = etree.QName('http://www.w3.org/1999/xhtml', 'html')>>> print(tag.localname)html>>> print(tag.namespace)http://www.w3.org/1999/xhtml>>> print(tag.text){http://www.w3.org/1999/xhtml}html>>> tag = etree.QName('{http://www.w3.org/1999/xhtml}html')>>> print(tag.localname)html>>> print(tag.namespace)http://www.w3.org/1999/xhtml>>> root = etree.Element('{http://www.w3.org/1999/xhtml}html')>>> tag = etree.QName(root)>>> print(tag.localname)html>>> tag = etree.QName(root, 'script')>>> print(tag.text){http://www.w3.org/1999/xhtml}script>>> tag = etree.QName('{http://www.w3.org/1999/xhtml}html', 'script')>>> print(tag.text){http://www.w3.org/1999/xhtml}script

lxml.etree allows you to look up the current namespaces defined for anode through the .nsmap property:

>>> xhtml.nsmap{None: 'http://www.w3.org/1999/xhtml'}

Note, however, that this includes all prefixes known in the context ofan Element, not only those that it defines itself.

>>> root = etree.Element('root', nsmap={'a': 'http://a.b/c'})>>> child = etree.SubElement(root, 'child',...  nsmap={'b': 'http://b.c/d'})>>> len(root.nsmap)1>>> len(child.nsmap)2>>> child.nsmap['a']'http://a.b/c'>>> child.nsmap['b']'http://b.c/d'

Therefore, modifying the returned dict cannot have any meaningfulimpact on the Element. Any changes to it are ignored.

Namespaces on attributes work alike, but as of version 2.3, lxml.etreewill make sure that the attribute uses a prefixed namespacedeclaration. This is because unprefixed attribute names are notconsidered being in a namespace by the XML namespace specification(section 6.2), so they may end up loosing their namespace on aserialise-parse roundtrip, even if they appear in a namespacedelement.

>>> body.set(XHTML + "bgcolor", "#CCFFAA")>>> print(etree.tostring(xhtml, pretty_print=True))<html xmlns="http://www.w3.org/1999/xhtml"> <body xmlns:html="http://www.w3.org/1999/xhtml" html:bgcolor="#CCFFAA">Hello World</body></html>>>> print(body.get("bgcolor"))None>>> body.get(XHTML + "bgcolor")'#CCFFAA'

You can also use XPath with fully qualified names:

>>> find_xhtml_body = etree.ETXPath( # lxml only !...  "//{%s}body" % XHTML_NAMESPACE)>>> results = find_xhtml_body(xhtml)>>> print(results[0].tag){http://www.w3.org/1999/xhtml}body

For convenience, you can use "*" wildcards in all iterators of lxml.etree,both for tag names and namespaces:

>>> for el in xhtml.iter('*'): print(el.tag) # any element{http://www.w3.org/1999/xhtml}html{http://www.w3.org/1999/xhtml}body>>> for el in xhtml.iter('{http://www.w3.org/1999/xhtml}*'): print(el.tag){http://www.w3.org/1999/xhtml}html{http://www.w3.org/1999/xhtml}body>>> for el in xhtml.iter('{*}body'): print(el.tag){http://www.w3.org/1999/xhtml}body

To look for elements that do not have a namespace, either use theplain tag name or provide the empty namespace explicitly:

>>> [ el.tag for el in xhtml.iter('{http://www.w3.org/1999/xhtml}body') ]['{http://www.w3.org/1999/xhtml}body']>>> [ el.tag for el in xhtml.iter('body') ][]>>> [ el.tag for el in xhtml.iter('{}body') ][]>>> [ el.tag for el in xhtml.iter('{}*') ][]

The E-factory provides a simple and compact syntax for generating XML andHTML:

>>> from lxml.builder import E>>> def CLASS(*args): # class is a reserved word in Python...  return {"class":' '.join(args)}>>> html = page = (...  E.html( # create an Element called "html"...  E.head(...  E.title("This is a sample document")...  ),...  E.body(...  E.h1("Hello!", CLASS("title")),...  E.p("This is a paragraph with ", E.b("bold"), " text in it!"),...  E.p("This is another paragraph, with a", "\n ",...  E.a("link", href="http://www.python.org"), "."),...  E.p("Here are some reservered characters: <spam&egg>."),...  etree.XML("<p>And finally an embedded XHTML fragment.</p>"),...  )...  )... )>>> print(etree.tostring(page, pretty_print=True))<html> <head> <title>This is a sample document</title> </head> <body> <h1 class="title">Hello!</h1> <p>This is a paragraph with <b>bold</b> text in it!</p> <p>This is another paragraph, with a <a href="http://www.python.org">link</a>.</p> <p>Here are some reservered characters: &lt;spam&amp;egg&gt;.</p> <p>And finally an embedded XHTML fragment.</p> </body></html>

The Element creation based on attribute access makes it easy to build up asimple vocabulary for an XML language:

>>> from lxml.builder import ElementMaker # lxml only !>>> E = ElementMaker(namespace="http://my.de/fault/namespace",...  nsmap={'p' : "http://my.de/fault/namespace"})>>> DOC = E.doc>>> TITLE = E.title>>> SECTION = E.section>>> PAR = E.par>>> my_doc = DOC(...  TITLE("The dog and the hog"),...  SECTION(...  TITLE("The dog"),...  PAR("Once upon a time, ..."),...  PAR("And then ...")...  ),...  SECTION(...  TITLE("The hog"),...  PAR("Sooner or later ...")...  )... )>>> print(etree.tostring(my_doc, pretty_print=True))<p:doc xmlns:p="http://my.de/fault/namespace"> <p:title>The dog and the hog</p:title> <p:section> <p:title>The dog</p:title> <p:par>Once upon a time, ...</p:par> <p:par>And then ...</p:par> </p:section> <p:section> <p:title>The hog</p:title> <p:par>Sooner or later ...</p:par> </p:section></p:doc>

One such example is the module lxml.html.builder, which provides avocabulary for HTML.

When dealing with multiple namespaces, it is good practice to defineone ElementMaker for each namespace URI. Again, note how the aboveexample predefines the tag builders in named constants. That makes iteasy to put all tag declarations of a namespace into one Python moduleand to import/use the tag name constants from there. This avoidspitfalls like typos or accidentally missing namespaces.

The ElementTree library comes with a simple XPath-like path languagecalled 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 notavailable.

In addition to a full XPath implementation, lxml.etree supports theElementPath language in the same way ElementTree does, even using(almost) the same implementation. The API provides four methods herethat you can find on Elements and ElementTrees:

  • iterfind() iterates over all Elements that match the pathexpression
  • findall() returns a list of matching Elements
  • find() efficiently returns only the first match
  • findtext() returns the .text content of the first match

Here are some examples:

>>> root = etree.XML("<root><a x='123'>aText<b/><c/><b/></a></root>")

Find a child of an Element:

>>> print(root.find("b"))None>>> print(root.find("a").tag)a

Find an Element anywhere in the tree:

>>> print(root.find(".//b").tag)b>>> [ b.tag for b in root.iterfind(".//b") ]['b', 'b']

Find Elements with a certain attribute:

>>> print(root.findall(".//a[@x]")[0].tag)a>>> print(root.findall(".//a[@y]"))[]

The .iter() method is a special case that only finds specific tagsin the tree by their name, not based on a path. That means that thefollowing commands are equivalent in the success case:

>>> print(root.find(".//b").tag)b>>> print(next(root.iterfind(".//b")).tag)b>>> print(next(root.iter("b")).tag)b

Note that the .find() method simply returns None if no match is found,whereas the other two examples would raise a StopIteration exception.

The lxml.etree Tutorial (2024)

FAQs

What is etree in lxml? ›

The lxml.etree module exposes another method that can be used to parse contents from a valid xml string — fromstring() xml = '<html><body>Hello</body></html>' root = etree. fromstring(xml) etree. dump(root) Link to GitHub. One important difference to note here is that fromstring() method returns an object of element.

What is the difference between XML and lxml? ›

The Python LXML module is a Python interface for the libxml2 and libxslt C parsers. It combines the speed of XML features with the high efficiency of the underlying C parses to create an API that closely follows the Python ElementTree API. The Lxml project follows the ElementTree concept.

What is the difference between Etree and ElementTree? ›

getiterator() method, ElementTree returns all elements in the tree, including comments and processing instructions. lxml. etree only returns real Elements, i.e. tree nodes that have a string tag name.

What does etree parse do? ›

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

Is Python lxml safe? ›

lxml is a Pythonic, mature binding for the libxml2 and libxslt libraries. It provides safe and convenient access to these libraries using the ElementTree API.

Is lxml faster than ElementTree? ›

The ElementTree API

The timings are somewhat close to each other, although cET can be several times faster than lxml for larger trees.

Is lxml better than BeautifulSoup? ›

However, lxml offers a balance between speed and feature-richness, while BeautifulSoup is favored for its ease of use and robustness in handling malformed HTML.

How does lxml work? ›

The lxml XML toolkit is a Pythonic binding for the C libraries libxml2 and libxslt. It is unique in that it combines the speed and XML feature completeness of these libraries with the simplicity of a native Python API, mostly compatible but superior to the well-known ElementTree API.

Can lxml parse HTML? ›

lxml provides a very simple and powerful API for parsing XML and HTML. It supports one-step parsing as well as step-by-step parsing using an event-driven API (currently only for XML).

What is the difference between xpath and ID? ›

XPATH are locators used to uniquely identify elements on a web page. The main difference between them is the way they locate elements. By.ID finds elements based on the id attribute of the HTML tag, which is supposed to be unique on the page. This method is generally faster and more reliable than other locators.

What is the difference between JSON and XML in PEGA? ›

JSON is favoured for its simplicity and compatibility with JavaScript, while XML offers strong schema support and hierarchical data organization, making it ideal for complex data structures and cross-platform interoperability.

What is the difference between JSON and XML tree? ›

XML stores data in a tree structure with namespaces for different data categories. The syntax of JSON is more compact and easier to read and write. The syntax of XML substitutes some characters for entity references, making it more verbose.

What is the best Python library to parse XML? ›

The Best Way To Parse XML in Python
  • Simple and built-in: xml. etree. ElementTree.
  • Small to medium documents with DOM support: minidom.
  • Large documents with stream processing: sax.
  • High performance with advanced features: lxml.
  • Easy handling of irregular XML/HTML: BeautifulSoup.
Nov 8, 2023

What is lxml in BeautifulSoup? ›

lxml is a high-performance XML and HTML parsing library for Python, known for its speed and comprehensive feature set. It supports XPath, XSLT, validation, and efficient handling of large documents, making it a preferred choice for web scraping and XML processing tasks.

How to use lxml parser in Python? ›

Implementing web scraping using lxml in Python
  1. Send a link and get the response from the sent link.
  2. Then convert response object to a byte string.
  3. Pass the byte string to 'fromstring' method in html class in lxml module.
  4. Get to a particular element by xpath.
  5. Use the content according to your need.
Oct 5, 2021

Who is Etree? ›

etree pioneered the standards for distributing lossless audio on the net and only permits its users to distribute the music of artists that allow the free taping and trading of their music.

What is the lxml package? ›

Introduction. The lxml XML toolkit is a Pythonic binding for the C libraries libxml2 and libxslt. It is unique in that it combines the speed and XML feature completeness of these libraries with the simplicity of a native Python API, mostly compatible but superior to the well-known ElementTree API.

How to parse XML in Python lxml? ›

How to Parse XML with LXML
  1. pip install lxml.
  2. from lxml import etree.
  3. filename = "file/location.xml" parser = etree. XMLParser() tree = etree. ...
  4. r=requests. ...
  5. foods = tree. ...
  6. for food in foods: print (food)
  7. python lxml_get_text. ...
  8. from lxml import etree import requests r=requests.

References

Top Articles
The World's Best Shortbread Is No Longer Sold—but We Got the Recipe
Easy Ottolenghi summer recipes: vegetables | Yotam Ottolenghi
It’s Time to Answer Your Questions About Super Bowl LVII (Published 2023)
55Th And Kedzie Elite Staffing
Hotels
Restored Republic January 20 2023
Cooking Chutney | Ask Nigella.com
Terrorist Usually Avoid Tourist Locations
Unity Stuck Reload Script Assemblies
Top 10: Die besten italienischen Restaurants in Wien - Falstaff
Moviesda Dubbed Tamil Movies
Truist Drive Through Hours
Lantana Blocc Compton Crips
Missing 2023 Showtimes Near Lucas Cinemas Albertville
Find your energy supplier
Jcpenney At Home Associate Kiosk
Brenna Percy Reddit
Hmr Properties
Colts Snap Counts
Conan Exiles Thrall Master Build: Best Attributes, Armor, Skills, More
Gem City Surgeons Miami Valley South
Cta Bus Tracker 77
Vigoro Mulch Safe For Dogs
Mccain Agportal
Wkow Weather Radar
European Wax Center Toms River Reviews
City Of Durham Recycling Schedule
Page 2383 – Christianity Today
Snohomish Hairmasters
Divide Fusion Stretch Hoodie Daunenjacke für Herren | oliv
Afni Collections
Dhs Clio Rd Flint Mi Phone Number
Abga Gestation Calculator
WPoS's Content - Page 34
Craigslist Boerne Tx
Used Safari Condo Alto R1723 For Sale
Donald Trump Assassination Gold Coin JD Vance USA Flag President FIGHT CIA FBI • $11.73
O'reilly Auto Parts Ozark Distribution Center Stockton Photos
Andhra Jyothi Telugu News Paper
D-Day: Learn about the D-Day Invasion
How to Get a Better Signal on Your iPhone or Android Smartphone
Discover Things To Do In Lubbock
Owa Hilton Email
Sofia Franklyn Leaks
Leland Nc Craigslist
Big Reactors Best Coolant
Ts In Baton Rouge
The Cutest Photos of Enrique Iglesias and Anna Kournikova with Their Three Kids
House For Sale On Trulia
How to Do a Photoshoot in BitLife - Playbite
Yoshidakins
Varsity Competition Results 2022
Latest Posts
Article information

Author: Ms. Lucile Johns

Last Updated:

Views: 5400

Rating: 4 / 5 (61 voted)

Reviews: 92% of readers found this page helpful

Author information

Name: Ms. Lucile Johns

Birthday: 1999-11-16

Address: Suite 237 56046 Walsh Coves, West Enid, VT 46557

Phone: +59115435987187

Job: Education Supervisor

Hobby: Genealogy, Stone skipping, Skydiving, Nordic skating, Couponing, Coloring, Gardening

Introduction: My name is Ms. Lucile Johns, I am a successful, friendly, friendly, homely, adventurous, handsome, delightful person who loves writing and wants to share my knowledge and understanding with you.