python写xml文件的操作实例

yipeiwu_com6年前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实现自定义顺序、排列写入数据到Excel的方法

本文实例讲述了Python实现自定义顺序、排列写入数据到Excel的方法。分享给大家供大家参考,具体如下: 例1. 数据框顺序写入Excel: data=a import xlsxw...

python 实现在一张图中绘制一个小的子图方法

python 实现在一张图中绘制一个小的子图方法

有时候为了直观展现图的信息,可以在大图中添加小子图的方式进行数据分析,如下图所示: 具体的代码如下:该图连接了数据库,当然重要的不是数据展示,而是添加子图的方法。 import m...

python使用mysqldb连接数据库操作方法示例详解

复制代码 代码如下:# -*- coding: utf-8 -*-     #mysqldb    import...

基于Python执行dos命令并获取输出的结果

这篇文章主要介绍了基于Python执行dos命令并获取输出的结果,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 import os...

Python使用循环神经网络解决文本分类问题的方法详解

Python使用循环神经网络解决文本分类问题的方法详解

本文实例讲述了Python使用循环神经网络解决文本分类问题的方法。分享给大家供大家参考,具体如下: 1、概念 1.1、循环神经网络 循环神经网络(Recurrent Neural Net...