我正在尝试将一些代码移植到 Python 3,该代码将xml.sax.make_parser
函数创建的解析器作为第二个参数传递xml.dom.minidom.parseString
给解析 XML 文档。
在 Python 3 中,解析器似乎无法将 XML 文档解析为bytes
,但在解析之前我不知道 XML 文档的编码。展示:
import xml.sax
import xml.dom.minidom
def try_parse(input, parser=None):
try:
xml.dom.minidom.parseString(input, parser)
except Exception as ex:
print(ex)
else:
print("OK")
euro = u"\u20AC" # U+20AC EURO SIGN
xml_utf8 = b"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
xml_cp1252 = b"<?xml version=\"1.0\" encoding=\"windows-1252\"?>"
test_cases = [
b"<a>" + euro.encode("utf-8") + b"</a>",
u"<a>" + euro + u"</a>",
xml_utf8 + b"<a>" + euro.encode("utf-8") + b"</a>",
xml_cp1252 + b"<a>" + euro.encode("cp1252") + b"</a>",
]
for i, case in enumerate(test_cases, 1):
print("%d: %r" % (i, case))
try_parse(case)
try_parse(case, xml.sax.make_parser())
蟒蛇2:
1: '<a>\xe2\x82\xac</a>'
OK
OK
2: u'<a>\u20ac</a>'
'ascii' codec can't encode character u'\u20ac' in position 3: ordinal not in range(128)
'ascii' codec can't encode character u'\u20ac' in position 3: ordinal not in range(128)
3: '<?xml version="1.0" encoding="utf-8"?><a>\xe2\x82\xac</a>'
OK
OK
4: '<?xml version="1.0" encoding="windows-1252"?><a>\x80</a>'
OK
OK
蟒蛇 3:
1: b'<a>\xe2\x82\xac</a>'
OK
initial_value must be str or None, not bytes
2: '<a>€</a>'
OK
OK
3: b'<?xml version="1.0" encoding="utf-8"?><a>\xe2\x82\xac</a>'
OK
initial_value must be str or None, not bytes
4: b'<?xml version="1.0" encoding="windows-1252"?><a>\x80</a>'
OK
initial_value must be str or None, not bytes
如您所见,默认解析器能够处理bytes
得很好,但我需要 SAX 解析器来处理参数实体。这个问题有什么解决方案(除了试图猜测bytes
解析前的编码)吗?