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

एलएक्सएमएल का उपयोग करना टैग "एफ 1" के लिए रिकर्सिव रूप से खोजना संभव है? मैंने खोजने की कोशिश की लेकिन यह केवल तत्काल बच्चों के लिए काम करता है।एलएक्सएमएल का उपयोग कर एक्सएमएल के टैग के लिए रिकर्सिवली कैसे खोजें?

मुझे लगता है कि मुझे इसके लिए सुंदर सूप के लिए जाना चाहिए !!!

उत्तर

56

आप रिकर्सिवली खोज करने के लिए XPath का उपयोग कर सकते हैं: सभी तत्वों कि पथ अभिव्यक्ति

findall() से मेल खाते

>>> 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() दोहराता मिलान तत्वों

find() की सूची लौटाता है कुशलता से केवल पहले रिटर्न मैच

findtext() ret पहले मैच की .text सामग्री urns

व्याख्यात्मक उदाहरण:

>>> 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

(इस उत्तर प्रासंगिक इस लिंक पर सामग्री से चयनात्मक चयन है)

संबंधित मुद्दे