以下是一个通过minidom模块写文件的完整示例,是在自己想做一个程序上面用到的,这个示例的目的是生成一个如下的格式的xml,文件格式为无BOM utf-8。
成xml的代码如下:
#-*- coding:utf-8 -*- import os import codecs import traceback import xml.dom.minidom as minidom def covert_to_unicode(msg): '''将转入的编码转换为unicode,只接受utf-8和unicode编码''' __re_str = None if isinstance(msg, unicode): __re_str = msg elif isinstance(msg, str): try: __re_str = msg.decode('utf-8') except Exception, errinfo: raise Exception, '%s,%s' % (errinfo, str(msg)) else: raise Exception, '%s 必须为str或unicode类型' % msg return __re_str class CreateCovXml(): def __init__(self, cov_xml_path): self.__cov_path = cov_xml_path self.__dom = None self.__root = None def _covert_code(self, msg): return covert_to_unicode(msg) def __create_new_node(self, node_name, node_text = None): '''为xml文件添加一个结点,其中node_text可以为空''' if self.__dom == None: raise Exception, '创建结点时,document对象还不存在' # 创建的是结点只有结点名 if None == node_text: return self.__dom.createElement(self._covert_code(node_name)) else: newNode = self.__dom.createElement(self._covert_code(node_name)) newText = self.__dom.createTextNode(self._covert_code(node_text)) newNode.appendChild(newText) return newNode def begin_cov(self): '''begin_cov(self) --> None 创建info.xml文档和根结点''' try: impl = minidom.getDOMImplementation() self.__dom = impl.createDocument(None, u'coverages', None) self.__root = self.__dom.documentElement except: traceback.print_exc() raise Exception, '创建info xml根结点失败' def add_cov(self, type, name, time, hrel, content, cover_rate): if self.__root == None: raise Exception, '创建结点时,root结点不存在对象不存不存在' #xml的属性设置 type_node = self.__create_new_node("Type", type) name_node = self.__create_new_node("Name", name) time_node = self.__create_new_node("Time", time) hrel_node = self.__create_new_node("Hrel", hrel) content_node = self.__create_new_node("Content", content) cover_line_node = self.__create_new_node("CoverRate", cover_rate) new_item_node = self.__create_new_node("Item") new_item_node.appendChild(type_node) new_item_node.appendChild(name_node) new_item_node.appendChild(time_node) new_item_node.appendChild(hrel_node) new_item_node.appendChild(content_node) new_item_node.appendChild(cover_line_node) self.__root.appendChild(new_item_node) def end_cov(self): try: f = open(self.__cov_path, 'wb') writer = codecs.lookup('utf-8')[3](f) self.__dom.writexml(writer, encoding='utf-8') writer.close() f.close() return True except Exception, err: traceback.print_exc() raise Exception, '写info.xml文件出错' if __name__ == '__main__': test = CreateCovXml('info.xml') test.begin_cov() test.add_cov( type = 'fx168', name = '', time = '8/24', hrel = 'http//////', content = '香港期金周二早盘升至1900美元上方', cover_rate = '68.38717' ) test.add_cov( type = 'fx168', name = '', time = '8/24', hrel = 'http//////', content = '香港期金周二早盘升至1900美元上方', cover_rate = '68.38717' ) test.end_cov() print 'done'
结果如下:
<?xml version="1.0" encoding="utf-8"?><coverages><Item><Type>fx168</Type><Name></Name><Time>8/24</Time><Hrel>http//////</Hrel><Content>香港期金周二早盘升至1900美元上方</Content><CoverRate>68.38717</CoverRate></Item><Item><Type>fx168</Type><Name></Name><Time>8/24</Time><Hrel>http//////</Hrel><Content>香港期金周二早盘升至1900美元上方</Content><CoverRate>68.38717</CoverRate></Item></coverages>
if __name__=="__main()":
允许这个程序在独立运行的时候做些有用的事情,不会在别的程序将它做为模块使用而引起冲突