迭代地解析大型XML文件而不使用DOM方法

Jan*_*ora 3 python xml lxml xml-parsing

我有一个xml文件

<temp>
  <email id="1" Body="abc"/>
  <email id="2" Body="fre"/>
  .
  .
  <email id="998349883487454359203" Body="hi"/>
</temp>
Run Code Online (Sandbox Code Playgroud)

我想阅读每个电子邮件标签的xml文件.也就是说,一次我想从中读取电子邮件id = 1..extract body,读取的电子邮件id = 2 ...并从中提取body ...等等

我尝试使用DOM模型进行XML解析,因为我的文件大小是100 GB ..这种方法不起作用.然后我尝试使用:

  from xml.etree import ElementTree as ET
  tree=ET.parse('myfile.xml')
  root=ET.parse('myfile.xml').getroot()
  for i in root.findall('email/'):
              print i.get('Body')
Run Code Online (Sandbox Code Playgroud)

现在,一旦我得到根...我不知道为什么我的代码无法解析.

使用iterparse时的代码抛出以下错误:

 "UnicodeEncodeError: 'ascii' codec can't encode character u'\u20ac' in position 437: ordinal not in range(128)"
Run Code Online (Sandbox Code Playgroud)

有人可以帮忙

Kie*_*ong 8

iterparse的一个例子:

import cStringIO
from xml.etree.ElementTree import iterparse

fakefile = cStringIO.StringIO("""<temp>
  <email id="1" Body="abc"/>
  <email id="2" Body="fre"/>
  <email id="998349883487454359203" Body="hi"/>
</temp>
""")
for _, elem in iterparse(fakefile):
    if elem.tag == 'email':
        print elem.attrib['id'], elem.attrib['Body']
    elem.clear()
Run Code Online (Sandbox Code Playgroud)

只需用您的真实文件替换fakefile即可.另请阅读此内容以获取更多详