xml文件,例:
读取:
from xml.etree import ElementTree as ElementTree
def read_xml():
tree = ElementTree.parse('movies.xml') #载入xml数据,使用ElementTree代表整个XML文档,Element代表这个文档树中的单个节点。
# print(tree)
root = tree.getroot() #获取根节点
# print(root)
movies = tree.findall('movie') #查找当前元素下匹配Element对象的直系节点
# print(movies)
all_movie = []
for movie in movies:
title = movie.get("title") #get,获取Element对象指定key对应的属性值,如果没有该属性,则返回default值
print(title)
# print(movie.getchildren())
# print(list(movie))
movie_info = {}
for child in movie: #Element对象,本身具有子元素,可以直接对Element进行迭代取值
# print(child)
# print(child.tag) #获取tag
# print(child.text) #获取节点text
movie_info[child.tag] = child.text
print(movie_info)
all_movie.append(movie_info)
print(all_movie)
read_xml()
def read_xml2():
tree = ElementTree.parse('movies.xml')
root = tree.getroot() #获取根节点
all_movie = []
for movie in root:
movie_info = {}
for child in movie:
movie_info[child.tag] = child.text
all_movie.append(movie_info)
print(all_movie)
read_xml2()
结果: