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' def get_root_tag(element): all = [] for target in root.xpath(element): parent_name = [] result = [] parent_name = find_parent_node(result, target) parent_name.insert(0, target.text) all.append(parent_name) return all 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) for item in name: print('<'.join(item))
A<One<Departments
B<Two<One<Departments
C<Three<Two<One<Departments
D<Department<Departments