for this xml
<Departments orgID="123" name="xmllist">
<Department>
<orgID>124</orgID>
<name>A</name>
<type>type a</type>
<status>Active</status>
<Department>
<orgID>125</orgID>
<name>B</name>
<type>type b</type>
<status>Active</status>
<Department>
<orgID>126</orgID>
<name>C</name>
<type>type c</type>
<status>Active</status>
</Department>
</Department>
</Department>
<Department>
<orgID>109449</orgID>
<name>D</name>
<type>type d</type>
<status>Active</status>
</Department>
</Departments>
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 = '''
... <Departments orgID="123" name="xmllist">
... <Department>
... <orgID>124</orgID>
... <name>A</name>
... <type>type a</type>
... <status>Active</status>
... <Department>
... <orgID>125</orgID>
... <name>B</name>
... <type>type b</type>
... <status>Active</status>
... <Department>
... <orgID>126</orgID>
... <name>C</name>
... <type>type c</type>
... <status>Active</status>
... </Department>
... </Department>
... </Department>
... <Department>
... <orgID>109449</orgID>
... <name>D</name>
... <type>type d</type>
... <status>Active</status>
... </Department>
... </Departments>
... '''
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With