Python3使用xml.dom.minidom和xml.etree模块儿解析xml文件封装函数的方法
总结了一下使用Python对xml文件的解析,用到的模块儿如下:
分别从xml字符串和xml文件转换为xml对象,然后解析xml内容,查询指定信息字段。
fromxml.dom.minidomimportparse,parseString
fromxml.etreeimportElementTree
importxml.dom.minidom
"""
GetXMLStringinfo查询属性值
response:xmlstring
tag:xmltag
element:xmlattribute
"""
defget_xml_info(response,element):
DOMTree=xml.dom.minidom.parseString(response)
returnDOMTree.documentElement.getAttribute(element)
"""
GetXMLStringinfo查询制定名称的特定标签id
xmlstring:xmlstr
returnconfigid
"""
defget_config_id_from_xml(xmlstring,scan):
root=ElementTree.fromstring(xmlstring)
configs=root.findall('config')
forconfiginconfigs:
config_name=config.find('name').text
ifconfig_name==scan:
returnconfig.attrib['id']
"""
GetXMLStringinfo查询指定id
xmlstring:xmlstr
returnreportid
"""
defget_report_id_from_xml(xmlstring):
root=ElementTree.fromstring(xmlstring)
report_id=root.find('report_id').text
returnreport_id
"""
GetXMLStringinfo
xmlstring:xmlstr
returnprogress
"""
defget_progress_from_xml(xmlstring):
root=ElementTree.fromstring(xmlstring)
task=root.find('task')
progress=float(task.find('progress').text)
ifprogress<0:
return100.0
else:
returnprogress
"""
GetXMLReportinfo从xml文件查询
file_path:reportpath
"""
defget_xml_report(file_path):
report={}
result_dicts={}
resultsList=[]
try:
root=ElementTree.parse(file_path)
except:
return{}
ifrootisnotNone:
creation_time=root.find("creation_time")
ifcreation_timeisnotNone:
report[creation_time.tag]=creation_time.text
ifroot.find("report")isnotNone:
scan_start=root.find("report").find("scan_start")
ifscan_startisnotNone:
ifscan_start.text:
report[scan_start.tag]=scan_start.text
results=root.getiterator("result")
ifresultsisnotNone:
forresultinresults:
ifresult.find("threat")isnotNone:
ifresult.find("threat").text!="Log":
resultsList.append(getResults(result))
report["Results"]=resultsList
returnreport
总结
以上所述是小编给大家介绍的Python3使用xml.dom.minidom和xml.etree模块儿解析xml文件封装函数的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!
