【问题标题】:How to make Python's ElementTree ignore lack of spaces between quotes and attributes?如何让 Python 的 ElementTree 忽略引号和属性之间缺少空格?
【发布时间】:2019-07-01 03:10:19
【问题描述】:

当我跑步时

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

我明白了

xml.etree.ElementTree.ParseError: 格式不正确(无效标记):第 1 行,第 11 列

这是因为""baz 之间没有空格。

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

有什么方法可以让ElementTree 对间距不那么迂腐,并像有空格一样解析它?

【问题讨论】:

  • 值得注意的是,这个类似问题中的解决方案会忽略错误,但不会恢复 baz 属性:stackoverflow.com/questions/13046240/…
  • 我认为这是不可能的。 XML 在设计上是“迂腐的”。你所拥有的不是 XML,符合标准的解析器拒绝它是正确的。
  • 如果我只是正则表达式这个问题,之后我会遇到 0 个问题吗?还是 2 个?

标签: python elementtree


【解决方案1】:

因为听上去可能还没有解决方案...

在出现更好的解决方案之前,这里有一个针对下一个可怜人的 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>

如果您发现其中的错误,Brownie 积分!

【讨论】:

  • 它破坏了正确的属性: print(xml_fixup('')) >>
猜你喜欢
  • 1970-01-01
  • 2013-11-19
  • 2021-10-02
  • 2018-05-25
  • 1970-01-01
  • 2021-12-31
  • 1970-01-01
  • 2015-09-22
  • 1970-01-01
相关资源
最近更新 更多