2012-07-09 3 views
8

lxml.etree.iterparse 함수를 사용하여 다음 파이썬 파일을 구문 분석하려고합니다.큰 xml 파일을 파이썬으로 구문 분석하기 - etree.parse 오류

"sampleoutput.xml"

<item> 
    <title>Item 1</title> 
    <desc>Description 1</desc> 
</item> 
<item> 
    <title>Item 2</title> 
    <desc>Description 2</desc> 
</item> 

은 내가 etree.iterparse (MYFILE) 나는 MYFILE = 개방 ("/ 사용자/에릭/데스크탑/wikipedia_map했다 호출하기 전에 Parsing Large XML file with Python lxml and Iterparse

의 코드를 시도 /sampleoutput.xml","r ")

그러나 다음과 같은 오류를 회전

Traceback (most recent call last): 
    File "/Users/eric/Documents/Programming/Eclipse_Workspace/wikipedia_mapper/testscraper.py", line 6, in <module> 
    for event, elem in context : 
    File "iterparse.pxi", line 491, in lxml.etree.iterparse.__next__ (src/lxml/lxml.etree.c:98565) 
    File "iterparse.pxi", line 543, in lxml.etree.iterparse._read_more_events (src/lxml/lxml.etree.c:99086) 
    File "parser.pxi", line 590, in lxml.etree._raiseParseError (src/lxml/lxml.etree.c:74712) 
lxml.etree.XMLSyntaxError: Extra content at the end of the document, line 5, column 1 

어떤 아이디어? 고맙습니다!

+1

그것은 XML 파일 형식이 잘못된 것일 수 :

다음 문서는 기존의 코드를 사용하여 올바른 결과를 생산? ' C0deH4cker

+1

lxml을 모르지만 예제가 유효한 XML이 아닙니다. XML 문서에는 단일 루트 요소가 있어야합니다. 너는 그렇지 않아. –

+1

자식 노드뿐만 아니라 루트 요소가 필요합니다. – pinkdawn

답변

7

정확히 하나의 최상위 태그가 없으면 XML의 형식이 올바르지 않습니다. 전체 문서를 <items></items> 태그로 묶어 샘플을 수정할 수 있습니다. 또한 사용중인 검색어 (description)와 일치하는 <desc/> 태그가 필요합니다.

<items> 
    <item> 
    <title>Item 1</title> 
    <description>Description 1</description> 
    </item> 
    <item> 
    <title>Item 2</title> 
    <description>Description 2</description> 
    </item> 
</items> 
+0

파일이 너무 커서 iterparse를 사용하여 파싱 할 때 메모리에로드하지 않으려면 어떻게해야합니까? –

3

내가 아는 한 xml.etree.ElementTree는 일반적으로 XML 파일에 "루트"요소, 즉 완전한 문서 구조를 둘러싸는 하나의 XML 태그가 포함될 것으로 기대합니다. 당신이 게시 한 오류 메시지에서 나는 이것도 여기에 문제가 있다고 가정합니다 :

'Line 5'는 두 번째 <item> 태그를 참조하므로 파이썬은 가정 된 루트 요소 다음에 더 많은 데이터가 있다고 불평한다고 추측합니다 즉 첫 번째 <item> 태그)가 닫혔습니다.

관련 문제