使用ElementTree操作XML文件

本文介绍如何使用Python的ElementTree模块进行XML文件的读取、修改与保存。通过实例展示了元素的查找、属性设置及子元素的创建过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

关于下载和安装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的使用,请参考另一篇我的博文。

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值