码迷,mamicode.com
首页 > 编程语言 > 详细

python创建xml文件

时间:2015-01-25 22:39:56      阅读:283      评论:0      收藏:0      [点我收藏+]

标签:

本文是一个使用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


python创建xml文件

标签:

原文地址:http://blog.csdn.net/smartfox80/article/details/43120135

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!