Как получить доступ к тегу глубоко внутри других тегов, используя xpath из xml? - PullRequest
1 голос
/ 29 апреля 2019

У меня есть глубокий вложенный тег xml Movie, доступ к которому я хочу получить напрямую с помощью xpath.

<?xml version='1.0' encoding='utf8'?>
<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>
</decade>
</genre>
</collection>
</xml>

Как получить доступ к тегу movie и его атрибутам? Я пытался использовать

root  = etee.tostring(above_xml)
print root.xpath("movie")
[]

но я ничего не получаю.

1 Ответ

0 голосов
/ 29 апреля 2019

Я не уверен, что это то, что вы ищете, но попробуйте это:

tree = lxml.etree.fromstring(xml_above, parser=lxml.etree.HTMLParser())
film =  tree.xpath("//movie/*/text()")
for i in film:
    print(i)

Вывод:

DVD
1981
PG

            'Archaeologist and adventurer Indiana Jones 
            is hired by the U.S. government to find the Ark of the 
            Covenant before the Nazis.'
...