python中lxml模块生成xml文件
2017-02-13 16:07
477 查看
用python自带的xml.etree.ElementTree模块和xml.dom.minidom模块生成xml文件标签的属性时,属性顺序会按照字典顺序重排,要想按照自己设定顺序来,可以使用lxml模块,lxml模块不是python自带的,需要自己安装,安装方法见上一篇博客。
lxml模块用法的例子如下:
lxml模块用法的例子如下:
from lxml import etree if __name__ == '__main__': #root = etree.Element("root") root = etree.Element("root",nsmap={'xsi': 'http://b.c/d'}) root.set("xsiinteresting", "totally") child1 = etree.SubElement(root, "child1" ) child1.set("interesting", "totally") child1.text = "TEXT" child2 = etree.SubElement(root, "child2") child2.set("name", "myattr1") child2.set("auto", "myattr2") child3 = etree.SubElement(child2, "child3") child3.text = "TEXT" child4 = etree.SubElement(child2, "child4") child4.text = "TEXT" child5 = etree.SubElement(child2, "child5") child6 = etree.SubElement(child5, "child6") child6.text = "TEXT" child7 = etree.SubElement(child5, "child7") child7.text = "TEXT" #root.append( etree.Element("child1") ) #root.append( etree.Element("child1", interesting="totally")) #child2 = etree.SubElement(root, "child2") #child3 = etree.SubElement(root, "child3") #root.insert(0, etree.Element("child0")) print etree.tostring(root, pretty_print=True) # write to file: tree = etree.ElementTree(root) tree.write('text.xml', pretty_print=True, xml_declaration=True, encoding='utf-8')
相关文章推荐
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例