使用特定的父标记解析 XML

Parse XML with a specific parent tag

<?xml version="1.0" encoding="utf-8"?>
  <ReturnHeader>
    <Bob>
      <Age>39</Age>
      <PhoneNum>2222</PhoneNum>
    </Bob>
    <John>
      <Age>70</Age>
      <PhoneNum>4444</PhoneNum>
    </John>
  </ReturnHeader>

根据上面的 XML,我试图只获取 Bob 的 phone。 (即,当 Bob 为“真”时)。

我需要以下输出:

电话号码 2222

我用 Xpath 尝试了 lxml,但没有成功。感谢任何帮助。

试试下面的方法

import xml.etree.ElementTree as ET

xml = '''<?xml version="1.0" encoding="utf-8"?>
  <ReturnHeader>
    <Bob>
      <Age>39</Age>
      <PhoneNum>2222</PhoneNum>
    </Bob>
    <John>
      <Age>70</Age>
      <PhoneNum>4444</PhoneNum>
    </John>
  </ReturnHeader>'''

NAME_TO_FIND = 'Bob'
root = ET.fromstring(xml)
for ele in root:
  if ele.tag == NAME_TO_FIND:
    print(f'The phone number of {NAME_TO_FIND} is {ele.find("PhoneNum").text}')
  else:
    print(f'I am not interested in the phone number of {ele.tag}')

输出

The phone number of Bob is 2222
I am not interested in the phone number of John