2014-05-18 4 views
1

XML 문서에서 문자열을 검색하고 해당 문자열을 포함하는 전체 요소 또는 요소를 인쇄하려고합니다.lxml etree에서 Xpath를 사용할 때 목록을 직렬화 할 수 없습니다.

<stuff> 

<article date="2014-05-18 17:14:44" title="Some stuff">More testing 
debug 
[done] 
<tags>Hello and stuff 
</tags></article> 

</stuff> 

그리고 마지막으로,이 내 오류가이 postf.txt에서 검색되고있는 XML은

post = open('postf.txt', 'r') 
postf = str(post.read()) 

root = etree.fromstring(postf) 

e = root.xpath('//article[contains(text(), "stuff")]') 

print etree.tostring(e, pretty_print=True) 

:이 지금까지 내 코드입니다

File "cliassis-1.2.py", line 107, in command 
    print etree.tostring(e, pretty_print=True) 
    File "lxml.etree.pyx", line 3165, in lxml.etree.tostring (src\lxml\lxml.etree.c:69414) 
TypeError: Type 'list' cannot be serialized. 

내가 이 작업을 수행하려면 검색 한 문자열이 포함 된 모든 요소를 ​​검색 한 다음 태그를 출력하십시오. 나는 시험과 물건을 가지고, 내가 '테스트'를 검색한다면, 나는 그래서 e 목록입니다.이 테스트 및 물건

답변

2
articles = root.xpath('//article[contains(text(), "stuff")]') 

for article in articles: 
    print etree.tostring(article, pretty_print=True) 

root.xpath는 파이썬 목록을 반환 "인쇄하고자합니다. etree.tostring 변환을 문자열에 LXML _Elements,.. 그것은 그래서 문자열로 목록 내부 _Elements을 인쇄 할 for-loop를 사용하여 문자열로 _Elements의 목록을 변환하지 않습니다

+0

이것은 완벽하게 작동했으며 설명을 통해 왜 작동하지 않는지 이해할 수있었습니다. 고맙습니다. :디 – Vales

1

당신은 또한 다음과 같은 기능을 결합 내장을 사용할 수 있습니다

.

e = root.xpath('//article[contains(text(), "stuff")]') strng = "".join(e)//list to string conversion print strng

관련 문제