这篇文章主要介绍了Python3使用xml.dom.minidom和xml.etree模块儿解析xml文件,封装函数的方法,代码简单易懂,非常不错,具有一定的参考借鉴价值,需要的朋友可以参考下
总结了一下使用Python对xml文件的解析,用到的模块儿如下:
分别从xml字符串和xml文件转换为xml对象,然后解析xml内容,查询指定信息字段。
from xml.dom.minidom import parse, parseString from xml.etree import ElementTree import xml.dom.minidom """ Get XML String info 查询属性值 response:xml string tag:xml tag element:xml attribute """ def get_xml_info(response, element): DOMTree = xml.dom.minidom.parseString(response) return DOMTree.documentElement.getAttribute(element) """ Get XML String info 查询制定名称的特定标签id xmlstring:xml str return config id """ def get_config_id_from_xml(xmlstring, scan): root = ElementTree.fromstring(xmlstring) configs = root.findall('config') for config in configs: config_name = config.find('name').text if config_name == scan: return config.attrib['id'] """ Get XML String info 查询指定id xmlstring:xml str return report id """ def get_report_id_from_xml(xmlstring): root = ElementTree.fromstring(xmlstring) report_id = root.find('report_id').text return report_id """ Get XML String info xmlstring:xml str return progress """ def get_progress_from_xml(xmlstring): root = ElementTree.fromstring(xmlstring) task = root.find('task') progress = float(task.find('progress').text) if progress <0: return 100.0 else: progress """ get xml report info 从xml文件查询 file_path : path def get_xml_report(file_path): {} r来源gao@!dai!ma.com搞$$代^@码!网esult_dicts={} resultslist=[] try: root except: if is not none: creation_time report[creation_time.tag]=creation_time.text root.find("report") scan_start scan_start.text: report[scan_start.tag]=scan_start.text results for result in results: result.find("threat") result.find("threat").text !="Log" resultslist.append(getresults(result)) report["results"]=resultsList report
总结
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!
以上就是Python3使用xml.dom.minidom和xml.etree模块儿解析xml文件封装函数的方法的详细内容,更多请关注gaodaima搞代码网其它相关文章!