在Python中解析XML所有标记都没有出现

2024-10-03 09:13:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用以下代码来解析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

Tags: formattitletypemovieitemwryearcollection
1条回答
网友
1楼 · 发布于 2024-10-03 09:13:56

对当前项使用“findall”。它返回一个列表,所以需要循环遍历它。你知道吗

collection = ET.fromstring(input)
lst = collection.findall('movie')
print ('Movie count:', len(lst))
for item in lst:
   print ('Movie Title', item.get("title"))

   movieTypes = item.findall('type')
   for movieType in movieTypes:
       print ('Type', movieType.text)
   print ('Format', item.find('format').text)
   print ('Year',item.find('year').text)
   print ""

相关问题 更多 >