我就在这里
分类: Python/Ruby
2013-02-18 14:15:53
#!python
#coding=GBK
################################################################################
# 通过ElementTree来操作XML
#
################################################################################
from xml.etree import cElementTree as ET
from xml.dom import minidom
def fomatTree(elem):
"""格式化XML的内容,用于输出,保存XML时并不需要"""
root_str = ET.tostring(elem, 'UTF-8')
reparse = minidom.parseString(root_str)
return reparse.toprettyxml(" ")
def createXML():
"""创建新的XML文件"""
head = """
"""
root = ET.fromstring(head)
elem = ET.Element("version", {'editor': 'magc', 'time': '20120523',})
elem2 = ET.Element('branch', {'editor': 'wang', 'time': '202203',})
root.append(elem)
root.append(elem2)
print fomatTree(root)
ET.ElementTree(root).write('samples.xml')
if __name__ == '__main__':
createXML()
转自:http://www.cnblogs.com/linux-sir/archive/2012/05/23/2515572.html