使用 elementtree 将数据解析为 dictionary/list

Parsing data with elementtree into a dictionary/list

我正在使用 Elementtree 解析 XML 文件(Nessus 数据)。我确定了 item.attrib,它看起来像是一本带有 'name': 'IPaddress' 的字典。我想将此数据添加到字典中,或者如果我只能将 ipaddress 访问到列表中。如何仅访问 name 的值?我尝试使用 item[0]/[1]/.attrib/text/ 的变体,但仍然没有成功。

当前代码

import elementtree.ElementTree as ET

def getDetails(nessus_file):
    host_list = []
    host_dict = {}
    try:
        tree = ET.parse(nessus_file)
        doc = tree.getroot()
        reporthost = doc.getiterator('ReportHost')
        for child in doc:
            if child.tag == 'Report':
                for item in child:
                    if item.tag == 'ReportHost':
                        print item.attrib

    except Exception as e:
        print e
        exit()
getDetails('file.nessus')

当前代码的示例输出

{'name': '172.121.26.80'}
{'name': '172.121.26.42'}
{'name': '172.121.26.41'}
{'name': '172.121.26.21'}
{'name': '172.121.26.15'}
{'name': '172.121.26.14'}

使用item.get('name')。有关详细信息,请参阅 https://docs.python.org/2/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.get