xml 转换conf 基于python

前端之家收集整理的这篇文章主要介绍了xml 转换conf 基于python前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

话部多说,xml格式如下:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <conf>
  3. <nova>192.168.0.1</nova>
  4. <glance>192.168.0.2</glance>
  5. <keystone>192.168.0.3</keystone>
  6. </conf>

conf文件如下:
  1. [service_ip_list]
  2. keystone = X.X.X.X
  3. nova = X
  4. glance = X

需要提取xml中的属性和值替换掉conf中的对应的配置,转换程序是用python写的
  1. #-*-coding:utf-8-*-
  2. from xml.dom import minidom
  3. doc = minidom.parse("conf.xml")
  4. conf_elements=doc.getElementsByTagName("conf")[0]
  5.  
  6. nova=conf_elements.getElementsByTagName("nova")[0]
  7. #print nova.nodeName,nova.childNodes[0].nodeValue
  8.  
  9. glance=conf_elements.getElementsByTagName("glance")[0]
  10. #print glance.nodeName,glance.childNodes[0].nodeValue
  11.  
  12. keystone=conf_elements.getElementsByTagName("keystone")[0]
  13. #keystone_ip=keystone.childNodes[0].nodeValue
  14. #print keystone.nodeName,keystone.childNodes[0].nodeValue
  15.  
  16. import ConfigParser
  17. import string,os,sys
  18.  
  19. cf=ConfigParser.ConfigParser()
  20. cf.read("ip-list.conf")
  21. cf.set("service_ip_list","keystone",keystone.childNodes[0].nodeValue)
  22. cf.set("service_ip_list","nova",nova.childNodes[0].nodeValue)
  23. cf.set("service_ip_list","glance",glance.childNodes[0].nodeValue)
  24. fh=open("ip-list.conf",'w')
  25. cf.write(fh)
  26. fh.close()

猜你在找的XML相关文章