for this xml
124
A
type a
Active
125
B
type b
Active
126
C
type c
Active
109449
D
type d
Active
How i can get all parents of a node using lxml etree in python.
Expected output : Input orgid=126 , it will return all the parents like ,
{'A':124,'B':125,'C':126}
解决方案
Using lxml and XPath:
>>> s = '''
...
...
... 124
... A
... type a
... Active
...
... 125
... B
... type b
... Active
...
... 126
... C
... type c
... Active
...
...
...
...
... 109449
... D
... type d
... Active
...
...
... '''
Using ancestor-or-self axis, you can find the node itself, parent, grandparent, ...
>>> import lxml.etree as ET
>>> root = ET.fromstring(s)
>>> for target in root.xpath('.//Department/orgID[text()="126"]'):
... d = {
... dept.find('name').text: int(dept.find('orgID').text)
... for dept in target.xpath('ancestor-or-self::Department')
... }
... print(d)
...
{'A': 124, 'C': 126, 'B': 125}