根据xml值获取元素所有父节点

from lxml import etree

s = '''
<Departments orgID="123" name="xmllist">
    <One>
        <orgID>124</orgID>
        <name>A</name>
        <type>type a</type>
        <status>Active</status>
            <Two>
                <orgID>125</orgID>
                <name>B</name>
                <type>type b</type>
                <status>Active</status>
                <Three>
                    <orgID>126</orgID>
                    <name>C</name>
                    <type>type c</type>
                    <status>Active</status>
                </Three>
            </Two>
    </One>
    <Department>
        <orgID>109449</orgID>
        <name>D</name>
        <type>type d</type>
        <status>Active</status>
    </Department>
</Departments>'''

root = etree.fromstring(s)
element = './/name[text()="C"]'


def get_root_tag(element):
    parent_name = ''
    result = []
    for target in root.xpath(element):
        parent_name = find_parent_node(result, target)
    return '<'.join(result)


def find_parent_node(result, target):
    parent_node = target.find('..')
    if not hasattr(parent_node, 'tag'):
        return result
    else:
        result.append(parent_node.tag)
        return find_parent_node(result, parent_node)


name = get_root_tag(element)
print(name)

 Three<Two<One<Departments

posted @ 2022-04-11 21:25  leecy125  阅读(184)  评论(0编辑  收藏  举报