自动创建xml文档

自动创建xml文档

import xml.etree.ElementTree as ET

print(dir(ET))    #ET里面有Element方法

root = ET.Element("new_list")       # new_list (根) xml文件里的开头和末尾的叫做根。

name = ET.SubElement(root,"name",attrib = {"enrolled":"yes"})  #在根下放一个子节点("name")
                                                               #attrib 存放着子节点里面的属性,可以存放多个属性
age = ET.SubElement(name,"age",attrib = {"checked":"no"})

sex = ET.SubElement(name,"sex")

sex.text = "male"


name2 = ET.SubElement(root,"name",attrib = {"enrolled":"no"})

age2 = ET.SubElement(name2,"age")

age.text = '19'

et = ET.ElementTree(root)

et.write("test.xml",encoding = "utf-8",xml_declaration = True)

ET.dump(root)

创建得出的文档如下

用什么方法能有规则的排列,待知。

<?xml version='1.0' encoding='utf-8'?>
<new_list><name enrolled="yes"><age checked="no">19</age><sex>male</sex></name><name enrolled="no"><age /></name></new_list>

  

  

posted @ 2018-04-17 22:47  Roc_Atlantis  阅读(220)  评论(0编辑  收藏  举报