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中mechanize库的简单使用示例

复制代码 代码如下:#!/usr/bin/env/ python#coding=utf-8import mechanizeimport cookielib # Cookie Jarcj...

python正则表达式及使用正则表达式的例子

正则表达式 正则表达用来匹配字符串 正则表达式匹配过程 依次拿出表达式和文本中的字符串进行比价 如果每个字符都能匹配,则匹配成功;一旦有匹配不成功的字符,则匹配失败 如果有...

django数据模型(Model)的字段类型解析

字段类型(Field types) 1、AutoField 它是一个根据 ID 自增长的 IntegerField 字段。通常,你不必直接使用该字段。如果你没在别的字段上指定主 键,Dj...

Python中断言Assertion的一些改进方案

Python Assert 为何不尽如人意? Python中的断言用起来非常简单,你可以在assert后面跟上任意判断条件,如果断言失败则会抛出异常。 >>>...

Python中pip更新和三方插件安装说明

Python中pip更新和三方插件安装说明

一、Python安装: 最新Python版本的下载和安装可以参考我的这篇博客,里面有步骤说明和注意事项。 二、手动更新pip:在安装第三方插件时如果提示pip版本需更新,可以这样做: 1...