使用ElementTree操作XML文件

关于下载和安装ElementTree,请参考官网:http://effbot.org/zone/element-index.htm

 

下面以这个XML文件为例:

 

<?xml version="1.0" encoding="UTF-8"?>

<collection shelf="New Arrivals">
	<movie title="Enemy Behind">
	   <type>War, Thriller</type>
	   <format>DVD</format>
	   <year>2003</year>
	   <rating>PG</rating>
	   <stars>10</stars>
	   <description>Talk about a US-Japan war</description>
	</movie>
	<movie title="Transformers">
	   <type>Anime, Science Fiction</type>
	   <format>DVD</format>
	   <year>1989</year>
	   <rating>R</rating>
	   <stars>8</stars>
	   <description>A schientific fiction</description>
	</movie>
	<movie title="Trigun">
	   <type>Anime, Action</type>
	   <format>DVD</format>
	   <episodes>4</episodes>
	   <rating>PG</rating>
	   <stars>10</stars>
	   <description>Vash the Stampede!</description>
	</movie>
	<movie title="Ishtar">
	   <type>Comedy</type>
	   <format>VHS</format>
	   <rating>PG</rating>
	   <stars>2</stars>
	   <description>Viewable boredom</description>
	</movie>
</collection>

读取XML文件:

from elementtree import ElementTree

root = ElementTree.parse('movies.xml').getroot()
movies = root.findall('.//movie')

for movie in movies:
  print '--------------------'
  print '@Title: ' + movie.attrib.get('title')
  #access to element directly by using XPATH
  e_type = movie.find('.//type')
  if(e_type != None):
    print e_type.tag + ' : ' + e_type.text

  for subElement in movie.getchildren():
    print '\t' + subElement.tag + ' : ' + subElement.text  

修改并保存XML文件:

from elementtree import ElementTree
from elementtree.ElementTree import Element

root = ElementTree.parse('movies.xml').getroot()

#Create a child element
e_movie = Element('movie')
root.append(e_movie)

#This is how you set an attribute on an element
e_movie.attrib['title'] = "Test element"

e_type = Element('type')
e_type.text = 'Test element - type'
e_movie.append(e_type)

e_format = Element('format')
e_format.text = 'Test element - format'
e_movie.append(e_format)

e_year = Element('year')
e_year.text = 'Test element - year'
e_movie.append(e_year)

e_rating = Element('rating')
e_rating.text = 'Test element - rating'
e_movie.append(e_rating)

e_stars = Element('stars')
e_stars.text = 'Test element - stars'
e_movie.append(e_stars)

e_description = Element('description')
e_description.text = 'Test element - description'
e_movie.append(e_description)


#Now lets write it to an .xml file on the hard drive

#Open a file
file = open("movies2.xml", 'w')

#Create an ElementTree object from the root element
ElementTree.ElementTree(root).write(file)

#Close the file like a good programmer
file.close()

如果要使用namespace的话,可以这样:

 

namespace = "http://xxx"

e = root.find('.//{%s}YourElementName' % namespace)
 

 

你可能会注意到,保存后的XML文件并没有缩进对齐。很遗憾的是ELementTree中没有提供相应的方法来实现这个功能。如果你确实需要对齐缩进的话,可以使用lxml。关于 lxml的使用,请参考另一篇我的博文。

 

 

 

 

 

 

 

你可能感兴趣的:(element)