Home > Back-end >  XML parsing under a specific parent tag
XML parsing under a specific parent tag

Time:03-09

<?xml version="1.0" encoding="utf-8"?>
  <ReturnHeader>
    <Bob>
      <PhoneNum>2222</PhoneNum>
      <Address>
        <AddressLine1>111 St</AddressLine1>
        <Zip>999</Zip>
      </Address>
    </Bob>
    <John>
      <PhoneNum>4444</PhoneNum>
      <Address>
        <AddressLine1>222 Ln</AddressLine1>
        <Zip>777</Zip> 
      </Address>    
    </John>
  </ReturnHeader>

From the above XML, I'm trying to get the ZIP Code of Bob. I need the following output:

Bob 999

Based on an answer here, I'm using the following code. But I can't get the text inside the address. Any help is appreciated.

import xml.etree.ElementTree as ET

NAME_TO_FIND = 'Bob'
root = ET.fromstring(xml)
for ele in root:
  if ele.tag == NAME_TO_FIND:
    print(ele.find("Zip").text)

CodePudding user response:

You can use xpath with iterfind()

name = 'Bob'
zip_code = next(root.iterfind(f'./{name}/Address/Zip'), None)
if zip_code is not None:
    print(zip_code.text) #999

name = 'John'
zip_code = next(root.iterfind(f'./{name}/Address/Zip'), None)
if zip_code is not None:
    print(zip_code.text) #777

  • Related