pythonxml读写_Python基础之读写xml总结

from xml.dom.minidom importparseimportxml.dom.minidomimportosdefis_xml_exist(xml_path):

xml_exist=os.path.exists(xml_path)if notxml_exist:returnFalsereturnTrue"""movie.xml

War, Thriller

DVD

2003

PG

10

Talk about a US-Japan war

Anime, Science Fiction

DVD

1989

R

8

A schientific fiction

Anime, Action

DVD

4

PG

10

Vash the Stampede!

Comedy

VHS

PG

2

Viewable boredom

"""

defread_movie_xml():

path= "movie.xml"

if notis_xml_exist(path):print("%s is not exist" %path)else:#使用minidom解析器打开XML文档

open_xml =parse(path)

root_node=open_xml.documentElement

shelf_attrib= "shelf"

ifroot_node.hasAttribute(shelf_attrib):print("Lable: %s\tAttrib: %s\t\tValue: %s" %(

root_node.nodeName, shelf_attrib, root_node.getAttribute(shelf_attrib)))print("")#在集合中获取所有电影

movie_node = "movie"movies=root_node.getElementsByTagName(movie_node)#打印每部电影的详细信息

for movie inmovies:print("**** Movie ****")if movie.hasAttribute("title"):print("Title: %s" % movie.getAttribute("title"))

type_movie= movie.getElementsByTagName('type')[0]print("Type: %s" %type_movie.childNodes[0].data)

format_movie= movie.getElementsByTagName('format')[0]print("Format: %s" %format_movie.childNodes[0].data)

rating_movie= movie.getElementsByTagName('rating')[0]print("Rating: %s" %rating_movie.childNodes[0].data)

descrip_movie= movie.getElementsByTagName('description')[0]print("Rating: %s" %descrip_movie.childNodes[0].data)print("")if __name__ == "__main__":

read_movie_xml()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值