Python UTF-8 XML 解析 (SUDS) : Removing 'invalid token'

标签 python xml soap unicode suds

这是处理 UTF-8 时的一个常见错误 - “无效标记”

在我的示例中,它来自于处理不尊重 unicode 字符的 SOAP 服务提供者,只是将值截断为 100 个字节并忽略第 100 个字节可能位于多字节字符的中间:例如:

<name xsi:type="xsd:string">浙江家庭教会五十人遭驱散及抓打 圣诞节聚会被断电及抢走物品(图、视频\xef\xbc</name>

最后两个字节是 3 字节 unicode 字符的剩余部分,在截断刀假定世界使用 1 字节字符之后。下一站,sax 解析器和:

xml.sax._exceptions.SAXParseException: <unknown>:1:2392: not well-formed (invalid token)

我不再关心这个角色了。它应该从文档中删除并允许 sax 解析器运行。

除了这些值之外,XML 回复在所有其他方面都是有效的。

问题:如何在不解析整个文档并重新发明 UTF-8 编码来检查每个字节的情况下删除这个字符?

使用:Python+SUDS

最佳答案

事实证明,SUDS 将 xml 视为类型“字符串”(不是 unicode),因此这些是编码值。

1) 过滤器:

badXML = "your bad utf-8 xml here"  #(type <str>)

#Turn it into a python unicode string - ignore errors, kick out bad unicode
decoded = badXML.decode('utf-8', errors='ignore')  #(type <unicode>)

#turn it back into a string, using utf-8 encoding.
goodXML = decoded.encode('utf-8')   #(type <str>)

2) SUDS:见https://fedorahosted.org/suds/wiki/Documentation#MessagePlugin

from suds.plugin import MessagePlugin
class UnicodeFilter(MessagePlugin):
    def received(self, context):
        decoded = context.reply.decode('utf-8', errors='ignore')
        reencoded = decoded.encode('utf-8')
        context.reply = reencoded

from suds.client import Client
client = Client(WSDL_url, plugins=[UnicodeFilter()])

希望这对某人有帮助。


注意:感谢John Machin !

参见:Why is python decode replacing more than the invalid bytes from an encoded string?

python issue8271关于 errors='ignore'可以在这里妨碍你。如果没有在 python 中修复此错误,'ignore' 将消耗接下来的几个字节以满足长度

during the decoding of an invalid UTF-8 byte sequence, only the
start byte and the continuation byte(s) are now considered invalid, instead of the number of bytes specified by the start byte

问题已修复:
Python 2.6.6 rc1
Python 2.7.1 rc1(以及 2.7 的所有 future 版本)
Python 3.1.3 rc1(以及 3.x 的所有 future 版本)

Python 2.5 及以下版本将包含此问题。

在上面的例子中,"\xef\xbc</name".decode('utf-8', errors='ignore')应该
返回"</name" ,但在“有漏洞”的 python 版本中,它返回 "/name" .

前四位 ( 0xe ) 描述了一个 3 字节的 UTF 字符,所以字节 0xef , 0xbc ,然后(错误地)0x3c ( '<' ) 被消耗。

0x3c不是一个有效的连续字节,它首先创建了无效的 3 字节 UTF 字符。

python 的固定版本仅删除第一个字节和仅有效的后续 字节,留下0x3c未消费

关于Python UTF-8 XML 解析 (SUDS) : Removing 'invalid token' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8719330/

相关文章:

xml - 如何使用vba解析XML

php - phpcurl 的 Soap Python 响应中的 NameError

python - 如何在 python 中从 WSDL 生成请求和响应模板

python - 重音字符的问题

python - 在 Pandas 中将 `replace` 与 `isnull` 组合

java - 将巨大的 XML 文件从 DOM 写入文件

java - 将 Java 日期对象映射到 XML 模式日期时间格式

php - 为什么在我的网络服务中调用操作时会出现此错误 "falseObject reference not set to an instance of an object."

python - 将 UIImage 从 BGR 转换为 RGB

python - Mechanize br.open 无限期挂起