简体   繁体   中英

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?

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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM