Python 使用elementtree将数据解析到字典/列表中
我正在使用Elementtree解析XML文件(Nessus数据)。我识别了item.attrib,它看起来是一个带有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
'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没有为“项”提供任何可供选择的值。