python写xml文件的操作实例
更新时间:2014年10月05日 15:03:49 投稿:shichen2014
这篇文章主要介绍了python写xml文件的操作实例,是非常常见的实用技巧,需要的朋友可以参考下
本文实例讲述了python写xml文件的操作的方法,分享给大家供大家参考。具体方法如下:
要生成的xml文件格式如下:
<?xml version="1.0" ?>
<!--Simple xml document__chapter 8-->
<book>
<title>
sample xml thing
</title>
<author>
<name>
<first>
ma
</first>
<last>
xiaoju
</last>
</name>
<affiliation>
Springs Widgets, Inc.
</affiliation>
</author>
<chapter number="1">
<title>
First
</title>
<para>
I think widgets are greate.You should buy lots of them forom
<company>
Spirngy Widgts, Inc
</company>
</para>
</chapter>
</book>
Python实现代码如下:
from xml.dom import minidom, Node
doc = minidom.Document()
doc.appendChild(doc.createComment("Simple xml document__chapter 8"))
#generate the book
book = doc.createElement('book')
doc.appendChild(book)
#the title
title = doc.createElement('title')
title.appendChild(doc.createTextNode("sample xml thing"))
book.appendChild(title)
#the author section
author = doc.createElement("author")
book.appendChild(author)
name = doc.createElement('name')
author.appendChild(name)
firstname = doc.createElement('first')
firstname.appendChild(doc.createTextNode("ma"))
name.appendChild(firstname)
lastname = doc.createElement('last')
name.appendChild(lastname)
lastname.appendChild(doc.createTextNode("xiaoju"))
affiliation = doc.createElement("affiliation")
affiliation.appendChild(doc.createTextNode("Springs Widgets, Inc."))
author.appendChild(affiliation)
#The chapter
chapter = doc.createElement('chapter')
chapter.setAttribute('number', '1')
title = doc.createElement('title')
title.appendChild(doc.createTextNode("First"))
chapter.appendChild(title)
book.appendChild(chapter)
para = doc.createElement('para')
para.appendChild(doc.createTextNode("I think widgets are greate.\
You should buy lots of them forom"))
company = doc.createElement('company')
company.appendChild(doc.createTextNode("Spirngy Widgts, Inc"))
para.appendChild(company)
chapter.appendChild(para)
print doc.toprettyxml()
希望本文所述对大家的Python程序设计有所帮助。
相关文章
pyinstaller打包单个exe后无法执行错误的解决方法
今天小编就为大家分享一篇pyinstaller打包单个exe后无法执行错误的解决方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2019-06-06
Python requests模块基础使用方法实例及高级应用(自动登陆,抓取网页源码)实例详解
这篇文章主要介绍了Python requests模块基础使用方法实例及高级应用(自动登陆,抓取网页源码,Cookies)实例详解,需要的朋友可以参考下2020-02-02
Python for Informatics 第11章之正则表达式(四)
这篇文章主要介绍了Python for Informatics 第11章之正则表达式(四) 的相关资料,需要的朋友可以参考下2016-04-04
Django中QuerySet查询优化之prefetch_related详解
prefetch_related()和select_related()的设计目的很相似,都是为了减少SQL查询的数量,但是实现的方式不一样,下面这篇文章主要给大家介绍了关于Django中QuerySet查询优化之prefetch_related的相关资料,需要的朋友可以参考下2022-11-11


最新评论