python生成xml文件

转自:http://www.2cto.com/kf/201501/372716.html
本文是一个使用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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值