使用Python解析大型xml文件--etree.parse错误

时间:2012-07-09 04:25:44

标签: python xml lxml

尝试使用lxml.etree.iterparse函数解析以下Python文件。

“sampleoutput.xml”

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

我尝试了Parsing Large XML file with Python lxml and Iterparse

中的代码

在etree.iterparse(MYFILE)调用之前我做了MYFILE = open(“/ Users / eric / Desktop / wikipedia_map / 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

任何想法?谢谢!

2 个答案:

答案 0 :(得分:11)

问题是,如果XML没有一个顶级标记,那么XML格式不正确。您可以通过将整个文档包装在<items></items>标记中来修复示例。您还需要<desc/>标记来匹配您正在使用的查询(description)。

以下文档使用现有代码生成正确的结果:

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

答案 1 :(得分:4)

据我所知,xml.etree.ElementTree通常希望XML文件包含一个“root”元素,即一个包含完整文档结构的XML标记。从您发布的错误消息中我会假设这也是问题所在:

'Line 5'指的是第二个<item>标签,所以我猜Python抱怨假定的根元素(即第一个<item>标签)关闭后会有更多的数据。

相关问题