Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I know a little of dom, and would like to learn about ElementTree. Python 2.6 has a somewhat older implementation of ElementTree, but still usable. However, it looks like it comes with two different classes: xml.etree.ElementTree and xml.etree.cElementTree. Would someone please be so kind to enlighten me with their differences? Thank you.

As an aside, you may find lxml.etree interesting; while a 3rd-party module, this is a superset of the ElementTree specification, and includes useful features such as real XPath support. Charles Duffy Feb 28, 2010 at 16:43

It is the same library (same API, same features) but ElementTree is implemented in Python and cElementTree is implemented in C.

If you can, use the C implementation because it is optimized for fast parsing and low memory use, and is 15-20 times faster than the Python implementation.

Use the Python version if you are in a limited environment (C library loading not allowed).

There are some subtle differences. In cElementTree, the findtext method did not have a default parameter (seen with Python 2.7.13). This can be easily replaced with findtext("...") or "defaultValue" , though. Florian Winter Aug 11, 2017 at 9:28 I think the main, arguably the only, reason for not using cElementTree is when the binaries are not available for a given platform (chipset/os combination). For example, ElementTree may work just fine out of the box on a niche platform that supports python but cElementTree binaries may not be available for that platform. Some of this is alluded to here . akhan Jul 6, 2018 at 21:56

Changed in version 3.3: This module will use a fast implementation whenever available. The xml.etree.cElementTree module is deprecated.

So for Python 3.3 and higher just use:

import xml.etree.ElementTree as ET

ElementTree is implemented in python while cElementTree is implemented in C. Thus cElementTree will be faster, but also not available where you don't have access to C, such as in Jython or IronPython or on Google App Engine.

Functionally, they should be equivalent.

Reference: docs.python.org/library/xml.etree.elementtree.html. "A C implementation of this API is available as xml.etree.cElementTree. " – S.Lott Feb 28, 2010 at 16:40

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.