求助,Python初学者,
从xml中获取所有数据后, data_list = xmlTree.findall('.//data') 例如这里我得到 10 行 现在,我只需要保留几行,其中属性“名称”的值与另一个列表 (inputID) 的元素匹配,其中包含三个 ID。 例如仅保留 3 行其名称属性与列表元素匹配
谢谢。
请您参考如下方法:
您可以使用 for 循环遍历每个元素,然后决定是否应删除每个元素。我使用了 Python 文档 ElementTree XML API供引用。
from xml.etree.ElementTree import ElementTree
tree = ElementTree()
# Test input
tree.parse("sample.xml")
# List containing names you want to keep
inputID = ['name1', 'name2', 'name3']
for node in tree.findall('.//data'):
# Remove node if the name attribute value is not in inputID
if not node.attrib.get('name') in inputID:
tree.getroot().remove(node)
# Do what you want with the modified xml
tree.write('sample_out.xml')
