Мне не удается в Python для печати заголовков фильмов из файла XML - PullRequest
0 голосов
/ 23 октября 2018

Я пытаюсь заставить python распечатать все названия фильмов в файле XML, но я не могу понять это.Я довольно новичок в Python, может кто-нибудь подсказать мне правильное направление?

Мой код пока:

import xml.etree.ElementTree as ET
tree = ET.parse('text.xml')
root = tree.getroot()

for elem in root:
    print(elem.find('movie').get('title'))

Файл XML:

<collection>
    <genre category="Action">
        <decade years="1980s">
            <movie favorite="True" title="Indiana Jones: The raiders of the lost Ark">
                <format multiple="No">DVD</format>
                <year>1981</year>
                <rating>PG</rating>
                <description>
                'Archaeologist and adventurer Indiana Jones
                is hired by the U.S. government to find the Ark of the
                Covenant before the Nazis.'
                </description>
            </movie>
               <movie favorite="True" title="THE KARATE KID">
               <format multiple="Yes">DVD,Online</format>
               <year>1984</year>
               <rating>PG</rating>
               <description>None provided.</description>
            </movie>
            <movie favorite="False" title="Back 2 the Future">
               <format multiple="False">Blu-ray</format>
               <year>1985</year>
               <rating>PG</rating>
               <description>Marty McFly</description>
            </movie>
        </decade>
     </genre>
 </collection>

Ответы [ 4 ]

0 голосов
/ 23 октября 2018

Метод поиска применяется только к дочерним элементам узла.
Вы забыли уровень 'декады'

import xml.etree.ElementTree as ET
tree = ET.parse('L:\\test (2).xml')
root = tree.getroot()

for elem in root:
    for movies in elem.find('decade'):
        print(movies.get('title'))

output

Indiana Jones: The raiders of the lost Ark
THE KARATE KID
Back 2 the Future
0 голосов
/ 23 октября 2018

Вот небольшой фрагмент, который вам может пригодиться.

import xml.etree.ElementTree as ET
tree = ET.parse('text.xml')
root = tree.getroot()

for genre in root:
    for decade in genre:
        for movie in decade:
            print("The movie name is ", movie.attrib['title']) # only get title from the dictionary

Для получения дополнительной информации о парсере xml перейдите по ссылке здесь

0 голосов
/ 23 октября 2018
import xml.etree.ElementTree as ET
tree = ET.parse('text.xml')
root = tree.getroot()

for movie in root.iter('movie'):
    print(movie.get('title'))

Вывод:

Indiana Jones: The raiders of the lost Ark
THE KARATE KID
Back 2 the Future

Вы можете взглянуть на xml.etree.ElementTree здесь

0 голосов
/ 23 октября 2018

Вы можете использовать BeautifulSoup как парсер XML и HTML, очень быстрый и простой для извлечения данных.

from bs4 import BeautifulSoup as bs
xml =open('xml-file').read() 
Soup = bs(xml, 'lxml')
[movie.get('title') for movie in Soup('movie')]

Вывод

['Indiana Jones: The raiders of the lost Ark',
 'THE KARATE KID',
 'Back 2 the Future']
...