我正在使用一个损坏的 XML-RPC 服务器,虽然我已提交支持请求来修复它,但存在一个错误,它将 utf-8 响应的字节长度报告为字符数,导致我收到的 XML 的截断。
我预计这个问题很快就会得到解决,但是我目前正在将其作为一组工具的一部分进行调查,并且确实需要让它发挥作用。目前,我有猴子修补的 xmlrpclib 来反转异常解析,并允许我手动向解析器提供响应的正确版本,但考虑到 XML 的性质,必须有一种方法以编程方式执行此操作,因此允许我使用XML-RPC 服务器就好像它没有这个 bug。
截断量只是结束标签的一部分,所以如果有一种内置方法来获取损坏的 xml 树,在所有标签都关闭的情况下转储它,然后解析它,这将允许我继续与我的工作 - 我目前正在考虑滚动自己的,但任何帮助将不胜感激,我无法想象我是第一个想要对 xml 执行错误更正的人,但如果我不这样做找到一个预先制定的解决方案,我会将我的解决方案推送到 git 并从这里链接它。
最佳答案
这是一个快速片段 - 关键是 sax 解析器在执行时生成事件,因此它们允许您处理内容直到它中断。
#!/usr/bin/env python
import sys
from xml.sax import handler, make_parser
class TagHandler(handler.ContentHandler):
def __init__(self):
handler.ContentHandler.__init__(self)
self.stack = []
def startElement(self, name, attrs):
self.stack.append(name)
def endElement(self, name):
# TODO: might want to just confirm that the element matches the top of the stack here
self.stack.pop()
def finish_document(self):
return "\n".join(["</%s>" % tag for tag in reversed(self.stack)])
parser = make_parser()
handler = TagHandler()
parser.setContentHandler(handler)
try:
parser.parse(sys.argv[1])
except:
# TODO: something more intelligent than just printing out the
# constructed end of the document. Like appending it to the source
# and repeating whatever you did to make this processing necessary.
print handler.finish_document()
关于修复损坏的 xml 的 Pythonic 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10604048/