0

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?

1 Answer 1

2

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']
Sign up to request clarification or add additional context in comments.

2 Comments

Works well! Thanks.
Or './/category[proxy = $proxy_type]/@name', proxy_type='doorbell')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.