這篇文章主要介紹了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:
return progress
"""
Get XML Report info 從xml文件查詢
file_path : report path
"""
def get_xml_report(file_path):
report = {}
result_dicts = {}
resultsList = []
try:
root = ElementTree.parse(file_path)
except:
return {}
if root is not None:
creation_time = root.find("creation_time")
if creation_time is not None:
report[creation_time.tag] = creation_time.text
if root.find("report") is not None:
scan_start = root.find("report").find("scan_start")
if scan_start is not None:
if scan_start.text:
report[scan_start.tag] = scan_start.text
results = root.getiterator("result")
if results is not None:
for result in results:
if result.find("threat") is not None:
if result.find("threat").text != "Log":
resultsList.append(getResults(result))
report["Results"] = resultsList
return report
寫到這裏,給大家推薦一個資源很全的python學習聚集地,點擊進入,這裏有資深程序員分享以前學習
心得,學習筆記,還有一線企業的工作經驗,且給大家精心整理一份python零基礎到項目實戰的資料,
每天給大家講解python最新的技術,前景,學習需要留言的小細節
總結
以上所述是小編給大家介紹的Python3使用xml.dom.minidom和xml.etree模塊兒解析xml文件封裝函數的方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回覆大家的。