Python3使⽤总结了⼀下使⽤Python对xml⽂件的解析,⽤到的模块⼉如下:
分别从xml字符串和xml⽂件转换为xml对象,然后解析xml内容,查询指定信息字段。from xml.dom.minidom import parse, parseString
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 Attribute(element)
"""
Get XML String info 查询制定名称的特定标签id
xmlstring:xml str
python处理xml文件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] =
if root.find("report") is not None:
scan_start = root.find("report").find("scan_start")
if scan_start is not None:
if :
report[scan_start.tag] =
results = iterator("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
总结
以上所述是⼩编给⼤家介绍的Python3使⽤xml.dom.minidom和模块⼉解析xml⽂件封装函数的⽅法,希望对⼤家有所帮助,如果⼤家有任何疑问请给我留⾔,⼩编会及时回复⼤家的。在此也⾮常感谢⼤家对⽹站的⽀持!
如果你觉得本⽂对你有帮助,欢迎转载,烦请注明出处,谢谢!

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。