2016-12-08 6 views
0

を表示されない:解析XMLすべてのタグは、私は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) 

私の出力があると私は何を得る:作品1が持っているか

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 

お知らせ2つの 'タイプ'。 'Movie' 1の2つの 'Type'を表示する代わりに、 'Movie' 1と2の両方の 'Type'を取得します。

私のforループにどこに問題があるのか​​理解できません。

所望の出力は次のようになります。 作品カウント:現在の項目の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 
+0

私はまた、「( 『)テキスト。印刷」種類「item.findall(』タイプ)」を使用してみましたが、それは私にエラー 『はAttributeError:『をリスト』オブジェクトには属性『テキスト』を持っていない』を与える –

答えて

1

使用 'の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 "" 
+0

それが本当にありがとうございました –

関連する問題