python xml .findall()返回空列表

时间:2019-10-31 12:29:51

标签: python xml-parsing elementtree

我尽力分析一个xml字符串,但是在搜索子元素时它返回一个空列表。我可以提供一个有效的python小提琴:

https://onlinegdb.com/SytNQIOcS

但这归结为:

root = ET.fromstring(xml_string)
print(root.findall('Race'))

有什么提示吗?看起来像是初学者的错误。

1 个答案:

答案 0 :(得分:0)

root = ET.fromstring(xml_string)
namespace = {'ns': 'http://ergast.com/mrd/1.4' }

for race in root.find('ns:RaceTable', namespace):
    round_num = race.get("round")
    circuit = race.find('ns:RaceName', namespace).text
    date = race.find("ns:Date", namespace).text
    time = race.find("ns:Time", namespace).text
    print(round_num, circuit, date, time)

错误:

  
      
  1. Element.findall()仅查找带有标签的元素,这些标签是当前元素的直接子元素。
  2.   
  3. 如果XML输入具有名称空间,带有前缀:prefix:sometag的前缀的标签和属性,则会扩展为{uri} sometag,其中   前缀将替换为完整的URI。另外,如果有默认值   名称空间,完整的URI会优先添加到所有非前缀的文件中   标签。   查看此文档https://docs.python.org/2/library/xml.etree.elementtree.html#parsing-xml-with-namespaces
  4.   

您可以使用类似的东西

相关问题