Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用elementtree将数据解析到字典/列表中_Python_Xml_Elementtree - Fatal编程技术网

Python 使用elementtree将数据解析到字典/列表中

Python 使用elementtree将数据解析到字典/列表中,python,xml,elementtree,Python,Xml,Elementtree,我正在使用Elementtree解析XML文件(Nessus数据)。我识别了item.attrib,它看起来是一个带有'name':'IPaddress'的字典。我想将这些数据添加到字典中,或者如果我可以访问列表中的IP地址。如何仅访问name的值?我尝试在[0]/[1]/.attrib/text/项上使用变体,但仍然没有成功 当前代码 import elementtree.ElementTree as ET def getDetails(nessus_file): host_list

我正在使用Elementtree解析XML文件(Nessus数据)。我识别了item.attrib,它看起来是一个带有
'name':'IPaddress'
的字典。我想将这些数据添加到字典中,或者如果我可以访问列表中的IP地址。如何仅访问
name
的值?我尝试在[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'}
当前代码的输出示例

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')
。有关详细信息,请参阅。

谢谢伯纳德。我不知道这个项目有一个get方法。我的IDE没有为“项”提供任何可供选择的值。