特定父标签下的XML解析

发布于 2025-01-12 10:20:13 字数 840 浏览 2 评论 0原文

<?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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

惟欲睡 2025-01-19 10:20:13

您可以将 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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文