¿Cómo encontrar recursivamente una etiqueta de XML usando LXML?


<?xml version="1.0" ?>
<data>
    <test >
        <f1 />
    </test >
    <test2 >
        <test3>
         <f1 />
        </test3>
    </test2>
    <f1 />
</data>

Usando lxml ¿es posible encontrar recursivamente la etiqueta " f1 "? Probé el método findall, pero solo funciona para niños inmediatos.

Creo que debería ir por BeautifulSoup para esto !!!

Author: Franck Dernoncourt, 2010-04-27

2 answers

Puede usar XPath para buscar recursivamente:

>>> 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>]
 63
Author: Max Shawabkeh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-04-27 18:38:18

iterfind() itera sobre todos los elementos que coinciden con la expresión path

findall() devuelve una lista de Elementos coincidentes

find() devuelve eficientemente solo la primera coincidencia

findtext() devuelve el .contenido del texto de la primera coincidencia

Ejemplos Ilustrativos:

>>> 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]"))
[]

Referencia: http://lxml.de/tutorial.html#elementpath

(Esta respuesta es una selección selectiva relevante del contenido en este enlace)

 24
Author: codersofthedark,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-05-07 19:52:26