2010-04-27 35 views
35
<?xml version="1.0" ?> 
<data> 
    <test > 
     <f1 /> 
    </test > 
    <test2 > 
     <test3> 
     <f1 /> 
     </test3> 
    </test2> 
    <f1 /> 
</data> 

使用lxml可以遞歸查找標記「f1」嗎?我試過findall方法,但它只適用於直接的孩子。如何使用LXML遞歸查找XML標記?

我想我應該爲BeautifulSoup這個!

回答

56

您可以使用XPath遞歸搜索:

>>> from lxml import etree 
>>> q = etree.fromstring('<xml><hello>a</hello><x><hello>b</hello></x></xml>') 
>>> q.findall('hello')  # Tag name, first level only. 
[<Element hello at 414a7c8>] 
>>> q.findall('.//hello') # XPath, recursive. 
[<Element hello at 414a7c8>, <Element hello at 414a818>] 
22

iterfind()迭代匹配路徑表達式

findall()所有元素,則返回匹配的元素

find()列表只高效地返回第一個匹配

findtext() ret甕第一匹配的內容的.text

例證:

>>> root = etree.XML("<root><a x='123'>aText<b/><c/><b/></a></root>") 
#Find a child of an Element: 
>>> print(root.find("b")) 
None 
>>> print(root.find("a").tag) 
a 
#Find an Element anywhere in the tree: 
>>> print(root.find(".//b").tag) 
b 
>>> [ b.tag for b in root.iterfind(".//b") ] 
['b', 'b'] 
#Find Elements with a certain attribute: 
>>> print(root.findall(".//a[@x]")[0].tag) 
a 
>>> print(root.findall(".//a[@y]")) 
[] 

參考: http://lxml.de/tutorial.html#elementpath

(此答案是有關從在此鏈接內容選擇性選擇)