2013-04-23 100 views
0

在我的項目中,我需要使用lxml.etree解析XML文檔。我是Python新手,所以我不明白,如何找到所有帶有標籤的類別。讓我們更準確地描述它。如何在Python 3中使用lxml?

我有一個像XML:

<cinema> 
    <name>BestCinema</name> 
    <films> 
    <categories> 
     <category>Action</category> 
     <category>Thriller</category> 
     <category>Soap opera</category> 
    </categories> 
    </films> 
</cinema> 

現在我需要得到所有類別的清單。在這種情況下,這將是:

 <category>Action</category> 
     <category>Thriller</category> 
     <category>Soap opera</category> 

我需要使用:

tree = etree.parse(file) 

謝謝,任何幫助是值得歡迎的。

回答

0

它應該是簡單的:

from lxml import etree 
el = etree.parse('input.xml') 
categories = el.xpath("//category") 
print(categories) 
... 

一切你應該在tutorial找到。