简体   繁体   中英

Python LXML findall then give a path

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 = ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM