解析包含无效字符的大型 XML 文件

21 浏览
0 Comments

解析包含无效字符的大型 XML 文件

我有一个1GB的xml文件,但是它包含一些无效字符,比如'&'。我想要在Python中解析它。为了做到这一点,我使用了如下的element tree:

import xml.etree.cElementTree as cElementTree
def main(): 
   context = cElementTree.iterparse('newscor.xml', events=("start", "end"))
   context = iter(context)
   event, root = context.__next__()
   for event, elem in context:
     if event == "start":
         if elem.tag == 'group': 
            elem.tail = None
            print ( elem.text)
         if elem.tag in ['group']:
            root.clear()                                               
main()

但是在这一行`for event, elem in context`,它给我报了以下错误:

`xml.etree.ElementTree.ParseError: not well-formed (invalid token)`

为了处理这个错误,我尝试使用带有`recover=True`的lxml解析器,如此链接中所描述的。然而,iterparse()在lxml中没有解析器参数。

因此,我还尝试了使用Sax,如此解决方案中所示,但是我不知道在哪里使用escape方法。

我应该使用什么方法来避免无效字符并解析这个大文件?

0