Python LXML findall then give a path

Viewed 19

How can I get the path for the founded elements?

tree = et.parse(inputFile)
root = tree.getroot()
items = root.findall(".//ns:COMPU-METHOD/[ns:CATEGORY='TEXTTABLE']", ns)
   for enums in items:
        enumName = enums.find('ns:SHORT-NAME', ns).text
        path = ?
1 Answers

It depends on what you mean by "path". You can get a list of elements going back to the root by calling each element's getparent in turn. LXML converts attribute and text nodes to dictionaries and strings, so any parent information is lost, but it works for the element

def get_element_path(e):
    elems = []
    while e:
        elems.append(e)
        e = e.getparent()
    return "/" + "/".join(e.tag for e in elems)

This will tell you the element names, but it is not a full XPATH to the object if any of the elements have more than 1 child element.

Related