<?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 的郵政編碼。我需要以下輸出:
鮑勃 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)
uj5u.com熱心網友回復:
您可以將 xpath 與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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/442391.html
