Q:

How to parse a deep nested XML in python

I am new to python, and I have a situation
<a>
<b>
  <c>
    <d>abcd</d>
       <e>
         <f>pqrs</f></e></d></c></b></a>

The algorithm is supposed to be if d has abcd , then find f, if f is present, return a true else return a false with abcd.
I would be grateful if there are someone can help me figure how to solve this issue.

A:

You could use a recursive XPath to attempt to find the matching tag and text and then another one to test for the presence of the other tag as follow:
import xml.etree.ElementTree as ET

def find_d(root):
    if root.findtext('.//d') == 'abcd':
        return root.find('.//f') is not None
    return False

xml_data = """<a>
<b>
  <c>
    <d>abcd</d>
       <e>
         <f>pqrs</f></e></c></b></a>"""

root = ET.fromstring(xml_data)
print find_d(root)

