2010-01-14 44 views
6

Por favor, ayúdame a resolver mi problema con lxml
(soy un novato en lxml).
¿Cómo puedo obtener "Comentario 1" en el archivo siguiente:XML analizando con lxml y Python

<?xml version="1.0" encoding="windows-1251" standalone="yes" ?> 
<!--Comment 1--> 
<a> 
    <!--Comment 2--> 
</a> 
+3

IIRC, el comentario 1 no es accesible para el analizador xml ya que es un comentario. puede que tenga que leer solo el archivo como texto. – KevinDTimm

+0

¿Piensas aceptar una respuesta? –

Respuesta

6
>>> from lxml import etree 
>>> tree = etree.parse('filename.xml') 
>>> root = tree.getroot() 
>>> print root.getprevious() 
<!--Comment 1--> 

O para estar seguro (puede haber más de una):

>>> for i in root.itersiblings(tag=etree.Comment, preceding=True): 
...  print i 
... 
<!--Comment 1--> 

utilizar el atributo .text si quieres extraer el texto del comentario.

12

Docs: the lxml tutorial, y buscar "Comentarios"

Código:

import lxml.etree as et 

text = """\ 
<?xml version="1.0" encoding="windows-1251" standalone="yes" ?> 
<!--Comment 1a--> 
<!--Comment 1b--> 
<a> waffle 
    <!--Comment 2--> 
    blah blah 
</a> 
<!--Comment 3a--> 
<!--Comment 3b--> 
""" 
print "\n=== %s ===" % et.__name__ 
root = et.fromstring(text) 

for pre in (True, False): 
    for comment in root.itersiblings(tag=et.Comment, preceding=pre): 
     print pre, comment 

for elem in root.iter(): 
    print 
    print isinstance(elem.tag, basestring), elem.__class__.__name__, repr(elem.tag), repr(elem.text), repr(elem.tail) 

Salida:

=== lxml.etree === 
True <!--Comment 1b--> 
True <!--Comment 1a--> 
False <!--Comment 3a--> 
False <!--Comment 3b--> 

True _Element 'a' ' waffle\n ' None 

False _Comment <built-in function Comment> 'Comment 2' '\n blah blah\n' 

Comentarios: no funciona con xml.etree.cElementTree