特定父标记下的XML解析 [英] XML parsing under a specific parent tag

查看:0
本文介绍了特定父标记下的XML解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<?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>

从上面的XML中,我试图获得Bob的邮政编码。我需要以下输出:

Bob 999

根据这里的答案,我使用以下代码。但我找不到地址里的文字。如有任何帮助,我们不胜感激。

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)

推荐答案

您可以使用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

这篇关于特定父标记下的XML解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆