特定父标签下的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)
<?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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以将 xpath 与 iterfind 一起使用()
You can use xpath with iterfind()