Python创建xml Python创建xml文件示例
聪明的狐狸 人气:0想了解Python创建xml文件示例的相关内容吗,聪明的狐狸在本文为您仔细讲解Python创建xml的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Python,创建,xml,下面大家一起来学习吧。
本文实例讲述了Python创建xml文件的方法。分享给大家供大家参考,具体如下:
这是一个使用ElementTree有关类库,生成xml文件的例子
# *-* coding=utf-8 from xml.etree.ElementTree import ElementTree from xml.etree.ElementTree import Element from xml.etree.ElementTree import SubElement from xml.etree.ElementTree import dump from xml.etree.ElementTree import Comment from xml.etree.ElementTree import tostring import os filename="book.xml" def CreateXml(): book =ElementTree() purOrder =Element("PurchaseOrder") book._setroot(purOrder) list = Element("account",{'idsn':'2390094'}) purOrder.append(list) item = Element("item1",{"sku":"abcd","qty":"4"}) SubElement(item,"Name").text="Potato Smasher" SubElement(item,"Description").text="Smash Potatoes like never before" purOrder.append(item) item = Element("item2",{"sku":"gfhi","qty":"40"}) SubElement(item,"Name").text="Beijing" SubElement(item,"Description").text="My Country" purOrder.append(item) indent(purOrder) return book def indent(elem,level=0): i ="\n"+level*" " print elem; if len(elem): if not elem.text or not elem.text.strip(): elem.text = i + " " for e in elem: print e indent(e,level+1) if not e.tail or not e.tail.strip(): e.tail =i if level and (not elem.tail or not elem.tail.strip()): elem.tail =i return elem if __name__ == '__main__': book =CreateXml() book.write(filename,"utf-8") #book.write("book2.xml","utf-8",True) #true is with xml declaration
PS:这里再为大家提供几款关于xml操作的在线工具供大家参考使用:
在线XML/JSON互相转换工具:
http://tools.softyun.net/code/xmljson
在线格式化XML/在线压缩XML:
http://tools.softyun.net/code/xmlformat
XML在线压缩/格式化工具:
http://tools.softyun.net/code/xml_format_compress
XML代码在线格式化美化工具:
http://tools.softyun.net/code/xmlcodeformat
希望本文所述对大家Python程序设计有所帮助。
加载全部内容