如何使 Python 的 ElementTree 忽略引号和属性之间缺少空格?

How to make Python's ElementTree ignore lack of spaces between quotes and attributes?

当我运行

from xml.etree import ElementTree
tree = ElementTree.fromstring('<foo bar=""baz=""></foo>')

我明白了

xml.etree.ElementTree.ParseError: not well-formed (invalid token): line 1, column 11

这是因为""baz之间缺少space。

我在第三方提供给我的 XML 文件中遇到了这个问题。

有没有办法让 ElementTree 对间距不那么迂腐,并像有 space 一样解析它?

因为这听起来像是一个解决方案,可能看不到...

在出现更好的解决方案之前,这里有一个为下一个可怜的灵魂提供的 hacky 解决方法...

def xml_fixup(s):  # give it the XML as a tring
    flags = re.DOTALL
    pat_quotes = '\"[^\"]*\"|\'[^\']*\''
    re_quotes = re.compile('(%s)([^>\s])' % pat_quotes, flags)  # TODO: cache
    re_pieces = re.compile('([^<]+)|(<)((?:[^\"\'>]+|%s)*)(>)' % pat_quotes, flags)  # TODO: cache
    pieces = re_pieces.findall(s)
    return s[:0].join(map(lambda m: m[0] or m[1] + re_quotes.sub('\1 \2', m[2]) + m[3], pieces))

print(xml_fixup('<foo bar=""baz=""></foo>'))  # <foo bar="" baz=""></foo>

如果您发现其中的错误,可加分!