python写xml文件的操作实例

yipeiwu_com5年前Python基础

本文实例讲述了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程序设计有所帮助。

相关文章

分享一个简单的python读写文件脚本

先来看一段创建文件并写入文本的代码,然后作介绍。 #!/usr/bin/env python 'makeFile.py -- create a file'...

图解python全局变量与局部变量相关知识

图解python全局变量与局部变量相关知识

这篇文章主要介绍了图解python全局变量与局部变量相关知识,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 了解全局变量和局部变量之前...

Python实现备份MySQL数据库的方法示例

本文实例讲述了Python实现备份MySQL数据库的方法。分享给大家供大家参考,具体如下: #!/usr/bin/env python # -*- coding:utf-8 -*-...

解决python读取几千万行的大表内存问题

Python导数据的时候,需要在一个大表上读取很大的结果集。 如果用传统的方法,Python的内存会爆掉,传统的读取方式默认在内存里缓存下所有行然后再处理,内存容易溢出 解决的方法: 1...

python 3.5实现检测路由器流量并写入txt的方法实例

python 3.5实现检测路由器流量并写入txt的方法实例

前言 本文主要给大家介绍了关于利用python 3.5检测路由器流量并写入txt的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍。 环境交代:win10+pyth...