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()