Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

access ElementTree node parent node

I am using the builtin Python ElementTree module. It is straightforward to access children, but what about parent or sibling nodes? - can this be done efficiently without traversing the entire tree?

like image 517
hoju Avatar asked Jan 31 '10 05:01

hoju


People also ask

How do I get parent nodes in Python?

Find node's parent using the path: parent_node = node. find('..')

How do I navigate to parent node in XPath?

A Parent of a context node is selected Flat element. A string of elements is normally separated by a slash in an XPath statement. You can pick the parent element by inserting two periods “..” where an element would typically be. The parent of the element to the left of the double period will be selected.

What is ElementTree?

The cElementTree module is a C implementation of the ElementTree API, optimized for fast parsing and low memory use. On typical documents, cElementTree is 15-20 times faster than the Python version of ElementTree, and uses 2-5 times less memory.


1 Answers

There's no direct support in the form of a parent attribute, but you can perhaps use the patterns described here to achieve the desired effect. The following one-liner is suggested (updated from the linked-to post to Python 3.8) to create a child-to-parent mapping for a whole tree, using the method xml.etree.ElementTree.Element.iter:

parent_map = {c: p for p in tree.iter() for c in p} 
like image 124
Vinay Sajip Avatar answered Oct 04 '22 21:10

Vinay Sajip