简体   繁体   English

Python LXML findall 然后给出路径

[英]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.您可以通过依次调用每个元素的getparent来获取返回根的元素列表。 LXML converts attribute and text nodes to dictionaries and strings, so any parent information is lost, but it works for the element LXML 将属性和文本节点转换为字典和字符串,因此任何父信息都会丢失,但它适用于元素

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.这将告诉您元素名称,但如果任何元素具有超过 1 个子元素,则它不是 object 的完整 XPATH。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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