ElementTree Issue - Search and remove elements

Stefan Behnel stefan_ml at behnel.de
Wed Oct 17 03:01:56 EDT 2012


Alain Ketterlin, 17.10.2012 08:25:
> It looks like you can't get the parent of an Element with elementtree (I
> would love to be proven wrong on this).

No, that's by design. ElementTree allows you to reuse subtrees in a
document, for example, which wouldn't work if you enforced a single parent.
Also, keeping parent references out simplifies the tree structure
considerably, saves space and time and all that. ElementTree is really
great for what it does.

If you need to access the parent more often in a read-only tree, you can
quickly build up a back reference dict that maps each Element to its parent
by traversing the tree once.

Alternatively, use lxml.etree, in which Elements have a getparent() method
and in which single parents are enforced (also by design).

Stefan





More information about the Python-list mailing list