Basically, using the standard xml.etree Python library, another visiting function is required. To achieve this, you can create a modified version of the iter method as follows:
def etree_iter_path(node, tag=None, path='.'): if tag == "*": tag = None if tag is None or node.tag == tag: yield node, path for child in node: _child_path = '%s/%s' % (path, child.tag) for child, child_path in etree_iter_path(child, tag, path=_child_path): yield child, child_path
Then you can use this function to iterate the tree from the root of the node:
from xml.etree import ElementTree xmldoc = ElementTree.parse(*path to xml file*) for elem, path in etree_iter_path(xmldoc.getroot()): print(elem, path)
source share