如何在使用ElementTree解析xml时移除无效字符(python)

2 投票
1 回答
4894 浏览
提问于 2025-04-18 08:43

我正在尝试用Python把大约15,000个xml文件导入到MongoDB,具体是用ElementTree这个库。发现大约5%的文件里有无效字符,主要是&符号。文件的编码是“ISO-8859-1”,而且在xml文件里也声明了编码。

请问有没有什么内置的方法可以跳过这个字符,或者自动把它转换成有效的字符呢?

这是我目前使用的代码:

    from pymongo import MongoClient
    import xml.etree.ElementTree as ET
    import os
    import sys


    def get_files(d):
            return [os.path.join(d, f) for f in os.listdir(d) if os.path.isfile(os.path.join(d,f))]

    files = get_files("/path/to/data")

    xmls = []
    for file in files:
        tree = ET.parse(file)
                root = tree.getroot()
        xmls.append(root)


    #Results in:
    In [113]: xmls = []
         ...: for file in files:
         ...:     tree = ET.parse(file)
         ...:     root = tree.getroot()
         ...:     xmls.append(root)
      File "<string>", line unknown
    ParseError: not well-formed (invalid token): line 223, column 74

果然,在下一个要解析的文档的第223行,第74列有一个&符号。

1 个回答

5

为了总结一下,我选择了这个方法:

我没有使用ElementTree,而是用了lxml,并且选择了它的恢复选项:

for file in files:
    parser = etree.XMLParser(ns_clean=True, recover = True)
    tree = etree.parse(file, parser=parser)
    root = tree.getroot()
    xmls.append(root)

这并没有解决根本的问题,但对于当前的任务来说已经足够了。

撰写回答