Home > Software design >  Parse XML with a specific parent tag
Parse XML with a specific parent tag

Time:03-08

<?xml version="1.0" encoding="utf-8"?>
  <ReturnHeader>
    <Bob>
      <Age>39</Age>
      <PhoneNum>2222</PhoneNum>
    </Bob>
    <John>
      <Age>70</Age>
      <PhoneNum>4444</PhoneNum>
    </John>
  </ReturnHeader>

From the above XML, I'm trying to get only the phone of Bob. (i.e., when Bob is 'True).

I need the following output:

PhoneNum 2222

I tried lxml with Xpath, but no luck. Any help is appreciated.

CodePudding user response:

Try the below

import xml.etree.ElementTree as ET

xml = '''<?xml version="1.0" encoding="utf-8"?>
  <ReturnHeader>
    <Bob>
      <Age>39</Age>
      <PhoneNum>2222</PhoneNum>
    </Bob>
    <John>
      <Age>70</Age>
      <PhoneNum>4444</PhoneNum>
    </John>
  </ReturnHeader>'''

NAME_TO_FIND = 'Bob'
root = ET.fromstring(xml)
for ele in root:
  if ele.tag == NAME_TO_FIND:
    print(f'The phone number of {NAME_TO_FIND} is {ele.find("PhoneNum").text}')
  else:
    print(f'I am not interested in the phone number of {ele.tag}')

output

The phone number of Bob is 2222
I am not interested in the phone number of John
  • Related