我使用以下代码来解析XML:
import xml.etree.ElementTree as ET
input = '''<collection shelf="New Arrivals">
<movie title="Enemy Behind">
<type>Wr, Thrller</type>
<type> Wwwwar, Thrilllllller</type>
<format>DVD</format>
<year>2003</year>
</movie>
<movie title="Transformers">
<type>Anime, Science Fiction</type>
<format>DVD</format>
<year>1989</year>
</movie>
</collection>'''
collection = ET.fromstring(input)
lst = collection.findall('movie')
print ('Movie count:', len(lst))
for item in lst:
print ('Movie Title', item.get("title"))
typelst = collection.findall('movie')
for item in typelst:
print ('Type', item.find('type').text)
print ('Format', item.find('format').text)
print ('Year',item.find('year').text)
我得到的结果是:
Movie count: 2
Movie Title Enemy Behind
Type Wr, Thrller
Type Anime, Science Fiction
Format DVD
Year 1989
Movie Title Transformers
Type Wr, Thrller
Type Anime, Science Fiction
Format DVD
Year 1989
注意电影1有两个“类型”。我没有显示'Movie'1'的两个'Type',而是同时显示'Movie'1和'Movie'2'的'Type'。你知道吗
我不明白问题出在哪里。你知道吗
所需输出应为: 电影计数:2
Movie Title Enemy Behind
Type Wr, Thrller
Type Wwwwar, Thrilllllller
Format DVD
Year 1989
Movie Title Transformers
Type Anime, Science Fiction
Format DVD
Year 1989
对当前项使用“findall”。它返回一个列表,所以需要循环遍历它。你知道吗
相关问题 更多 >
编程相关推荐