问题
你要做的是
解析,因为此行已经完成了解析:
tree = ET.parse(file_name, parser=parser)
你不需要通过
parser=XMLParser
阅读参考:
xml.etree.ElementTree.parse
您的示例代码循环
ElementTree
四次
for ele in tree.findall('update'):
cveList = [
ele.find('references/reference').get('id') if ele.find('references/reference').get('type') == 'cve' else None
for cve in ele.find('references/reference')]
.find...
,将循环,直到找到所请求的元素为止。
你可以得到所有
reference
元素
一
import xml.etree.ElementTree as ET
file_name = "test/updateinfo.xml"
tree = ET.parse(file_name)
cveList = []
for reference in tree.findall('update/references/reference'):
if reference.attrib.get('type') == 'cve':
cveList.append(reference.attrib.get('id'))
print(cveList)
:
['CVE-2017-7793', 'CVE-2017-7810', 'CVE-2017-7814', 'CVE-2017-7818', 'CVE-2017-7819', 'CVE-2017-7823', 'CVE-2017-7824']
评论
# Findall 'update' Elements in tree
for update in tree.findall('update'):
# Findall 'references/reference' in update
for reference in update.findall('references/reference'):
if reference.attrib.get('type') == 'cve':
# Find Element with tag <title> in update
title = update.find('title').text
# Append a Dict with keys 'title' and 'id'
cveList.append({'title': title, 'id': reference.get('id')})
[{'id': 'CVE-2017-7793', 'title': 'Critical: firefox security update'}, {'id': 'CVE-2017-7810', 'title': 'Critical: firefox security update'}, {'id': 'CVE-2017-7814', 'title': 'Critical: firefox security update'}, {'id': 'CVE-2017-7818', 'title': 'Critical: firefox security update'}, {'id': 'CVE-2017-7819', 'title': 'Critical: firefox security update'}, {'id': 'CVE-2017-7823', 'title': 'Critical: firefox security update'}, {'id': 'CVE-2017-7824', 'title': 'Critical: firefox security update'}]
用P测试ython:2.7.9