user2643864 user2643864 - 3 months ago 15
Python Question

How to get the parent xml element after finding a child xml element using lxml and python

I have a bit of a tough nut to crack. It has been so long since I've used LXML that I need some help to get started. I have an XML file that has a list of categories and proxy elements. Please see the snippet below:

<categories>
<category name="Light">
<proxy>fan</proxy>
</category>
<category name="UI">
<proxy>doorbell</proxy>
</category>
</categories>


What I would like to do is search through all the proxy elements to find "doorbell". If found, I would like to know the name of the parent element it came from. So in the above example, doorbell would be found under the parent category elementnamed "UI". In the end, I just need the value of the "name" attribute for the parent element in which the proxy fell under.

Any gurus out there want to help me tackle this?

Answer

If all you need is the name, might as well do it all in one search:

import lxml.etree as ET

root = ET.XML('''
<categories>
  <category name="Light">
    <proxy>fan</proxy>
  </category>
  <category name="UI">
    <proxy>doorbell</proxy>
  </category>
</categories>
''')

category_names = root.xpath(
  './/proxy[. = $proxy_type]/parent::category/@name',
  proxy_type='doorbell')

print category_names

...emits, as one would expect:

['UI']
Comments