gpt4 book ai didi

python - 在 Python 中过滤 xml 数据

转载 作者:太空宇宙 更新时间:2023-11-04 06:21:24 25 4
gpt4 key购买 nike

求助,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')

关于python - 在 Python 中过滤 xml 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11866720/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com