[XML-SIG] How do I replace multiple elements in a document?(using ElementTree)

Fredrik Lundh fredrik at pythonware.com
Wed Nov 30 17:27:38 CET 2005

Tony McDonald wrote:

> I did have this,
> from elementtree.ElementTree import XML, ElementTree, Element,
> SubElement, dump
> and went to this;
> from cElementTree import XML, ElementTree, Element, SubElement, dump
> Which imports fine, but there's something amiss because;
> root = ElementTree(file=filename)
> ...
> elements = root.getiterator()
> print "LEN", len(elements)
> which gave 634 elements using python ElementTree but gives len() of
> unsized object when using the eElementTree version, and there does
> seem to be something amiss ...

the getiterator method is defined to return "something that you can
iterate over", which is not necessarily a sequence object.

in ElementTree, it happens to be a list (at least in the 1.2 series), but
cElementTree returns a generator instead.

no matter what version you're using, this

    for elem in root.getiterator():

is guaranteed to work.  if you want a list, you can always use the list
constructor. e.g.

    print "LEN", len(list(root.getiterator()))


More information about the XML-SIG mailing list