用Python的方式修复损坏的xm

2024-04-26 03:57:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在处理一个损坏的XML-RPC服务器,虽然我已经提交了一个支持请求来修复它,但是有一个错误,它将utf-8响应的字节长度报告为字符计数,导致我接收到的XML被截断。在

我希望这个问题很快会被修复,但我目前正在调查这是一套工具的一部分,真的需要让它发挥作用。目前,我已经对xmlrpclib进行了monkey补丁,以逆转异常时的解析,并允许我手动向解析器提供一个正确版本的响应,但是考虑到XML的性质,必须有一种方法可以通过编程来实现这一点,因此允许我使用XML-RPC服务器,就好像它没有这个bug一样。在

截断的数量只是结束标记的一部分,所以如果有一种内置的方法来获取损坏的xml树,在关闭所有标记的情况下转储它,然后解析它,这将使我能够继续我的工作—我目前正在寻找自己的工作,但如果有任何帮助,我们将不胜感激,我无法想象我是第一个想在xml上执行错误更正的人,但是如果我找不到预先制定的解决方案,我会把我的解决方案推到git上,然后从这里链接它。在


Tags: 工具方法标记服务器字节报告错误xml
1条回答
网友
1楼 · 发布于 2024-04-26 03:57:24

这里有一个简短的片段-关键是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()

相关问题 更多 >