2010-01-14 4 views
6

lxml 내 문제를 해결하는 데 도움이
(저는 lxml에 초보자입니다).
어떻게 다음 파일에서 "코멘트 1"을 얻을 수 있습니다 :lxml 및 Python을 사용하여 XML 구문 분석

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

IIRC, 주석 1이므로 xml 파서는 주석이므로 주석 1에 액세스 할 수 없습니다. 텍스트로만 파일을 읽어야 할 수도 있습니다. – KevinDTimm

+0

대답을 수락 하시겠습니까? –

답변

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

또는 확인하기 (하나 이상이있을 수 있습니다) :

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

.text 속성 경우 사용 주석의 텍스트를 추출하려고합니다.

12

문서 : the lxml tutorial 및 "설명"을 검색

코드 :

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) 

출력 :

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

댓글 : xml.etree.cElementTree

작동하지 않습니다