Python-ETree element.find在部分匹配上

Python-ETree element.find在部分匹配上,python,elementtree,Python,Elementtree,下面的代码片段循环遍历几个xml文件,并从每个xml文件中提取字典中的3个“列”。其中一个XML的第一个字段名为“IndexName”而不是“IndexID”。如何使用单个字段列表(如 field_list = ['Index*', 'CompositeSpread', 'CompositePrice',] 要查找部分匹配项,请执行以下操作: strXpath = "./row" field_list = ['IndexID', 'CompositeSpread', 'CompositePr

下面的代码片段循环遍历几个xml文件,并从每个xml文件中提取字典中的3个“列”。其中一个XML的第一个字段名为“IndexName”而不是“IndexID”。如何使用单个字段列表(如

field_list = ['Index*', 'CompositeSpread', 'CompositePrice',]
要查找部分匹配项,请执行以下操作:

strXpath = "./row"

field_list = ['IndexID', 'CompositeSpread', 'CompositePrice',]
field_list1 = ['IndexName', 'CompositeSpread', 'CompositePrice',]

tree = ET.parse(file_path)
root = tree.getroot()

value_list = []
for el in root.findall(strXpath):
    value_list.append([el.find(x).text for x in field_list])

我提出的解决方案是在
字段列表中同时使用
'IndexID'
'IndexName'
字段,并检查
是否在列表中el.find(x)不是None

import xml.etree.ElementTree as ET

    strXpath = "./row"

    field_list = ['IndexName', 'IndexID', 'CompositeSpread', 'CompositePrice',]

    tree = ET.parse(file_path)
    root = tree.getroot()

    value_list = []
    for el in root.findall(strXpath):
        value_list.append([el.find(x).text for x in field_list if el.find(x) is not None])

如果您同时获得这两个字段,这也将起作用,它将同时添加这两个字段。已同意。在我的例子中,这些字段是互斥的,因为它们源于不同文件不一致的命名约定。但每个xml文件只有一个这样的字段。