python写xml文件_用python写xml文件
def writeInfoToXml(filename, config_id, obj_name):
from xml.dom.minidom import Document
'''
eg:
Web Servers
Denial of Service
General
'''
# 創(chuàng)建dom文檔
doc = Document()
# 創(chuàng)建根節(jié)點(diǎn)
modify_node = doc.createElement('modify_config')
# 修改或添加節(jié)點(diǎn)中元素內(nèi)容
modify_node.setAttribute("config_id", config_id)
# 根節(jié)點(diǎn)插入dom樹
doc.appendChild(modify_node)
# 每一組信息先創(chuàng)建節(jié)點(diǎn),然后插入到父節(jié)點(diǎn)下
nvtSlect = doc.createElement('nvt_selection')
modify_node.appendChild(nvtSlect)
# 從數(shù)據(jù)庫查詢需要掃描的項(xiàng)
vulnerData = nova_get_vulnerdata_from_db(obj_name)
# 依次將vulnerData中的每一組元素提取出來,創(chuàng)建對應(yīng)節(jié)點(diǎn)并插入dom樹
for idx, sub_data in enumerate(vulnerData):
for name, oid_list in sub_data.items():
# 創(chuàng)建節(jié)點(diǎn)
family = doc.createElement('family')
# 創(chuàng)建下的文本節(jié)點(diǎn)
family_text = doc.createTextNode(name)
# 將文本節(jié)點(diǎn)插入到下
family.appendChild(family_text)
# 將插入到父節(jié)點(diǎn)下
nvtSlect.appendChild(family)
for oid in oid_list:
# 創(chuàng)建nvt節(jié)點(diǎn)
nvt_node = doc.createElement('nvt')
# 修改或添加節(jié)點(diǎn)中元素內(nèi)容
nvt_node.setAttribute("oid", oid)
# 將nvt節(jié)點(diǎn)插入到父節(jié)點(diǎn)nvtSlect
nvtSlect.appendChild(nvt_node)
cmd = "rm -rf {}".format(filename)
subprocess.check_output(cmd, shell=True)
# 將dom對象寫入本地xml文件
with open(filename, 'w') as f:
doc.writexml(f, indent='',addindent='\t',newl='\n',encoding='UTF-8')
總結(jié)
以上是生活随笔為你收集整理的python写xml文件_用python写xml文件的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java多线程_1_Java内存模型_内
- 下一篇: C++_虚继承_虚函数_纯虚函数(多继承