介绍 python xmltodict 解析xml gbk 编码问题的解决方法
错误提示
1
ValueError: multi-byte encodings are not supported
解决实例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# -*- coding: utf-8 -*-
import json
import xmltodict
d = xmltodict.parse("""<?xml version="1.0" encoding="GBK"?>
<request>
<head>
<h_exch_code>880061</h_exch_code>
<h_bank_no>0000</h_bank_no>
<h_branch_id>B00000</h_branch_id>
<h_fact_date>20110224</h_fact_date>
<h_fact_time>14:49:20</h_fact_time>
<h_exch_date>20110224</h_exch_date>
<h_serial_no>12345678</h_serial_no>
<h_rsp_code></h_rsp_code>
<h_rsp_msg></h_rsp_msg>
</head>
<body>
<record>
<user_id>1204300001</user_id>
<user_pwd>e10adc3949ba59abbe56e057f20f883e</user_pwd>
<login_ip>127.0.0.1</login_ip>
</record>
</body>
</request>
""", encoding="utf-8")
print d
print json.dumps(d)
print xmltodict.unparse(d, encoding='GBK')
注意两个 encoding
输出
1
2
3
4
5
6
OrderedDict([(u'request', OrderedDict([(u'head', OrderedDict([(u'h_exch_code', u'880061'), (u'h_bank_no', u'0000'), (u'h_branch_id', u'B00000'), (u'h_fact_date', u'20110224'), (u'h_fact_time', u'14:49:20'), (u'h_exch_date', u'20110224'), (u'h_serial_no', u'12345678'), (u'h_rsp_code', None), (u'h_rsp_msg', None)])), (u'body', OrderedDict([(u'record', OrderedDict([(u'user_id', u'1204300001'), (u'user_pwd', u'e10adc3949ba59abbe56e057f20f883e'), (u'login_ip', u'127.0.0.1')]))]))]))])
{"request": {"head": {"h_exch_code": "880061", "h_bank_no": "0000", "h_branch_id": "B00000", "h_fact_date": "20110224", "h_fact_time": "14:49:20", "h_exch_date": "20110224", "h_serial_no": "12345678", "h_rsp_code": null, "h_rsp_msg": null}, "body": {"record": {"user_id": "1204300001", "user_pwd": "e10adc3949ba59abbe56e057f20f883e", "login_ip": "127.0.0.1"}}}}
<?xml version="1.0" encoding="GBK"?>
<request><head><h_exch_code>880061</h_exch_code><h_bank_no>0000</h_bank_no><h_branch_id>B00000</h_branch_id><h_fact_date>20110224</h_fact_date><h_fact_time>14:49:20</h_fact_time><h_exch_date>20110224</h_exch_date><h_serial_no>12345678</h_serial_no><h_rsp_code></h_rsp_code><h_rsp_msg></h_rsp_msg></head><body><record><user_id>1204300001</user_id><user_pwd>e10adc3949ba59abbe56e057f20f883e</user_pwd><login_ip>127.0.0.1</login_ip></record></body></request>
本文网址: https://pylist.com/topic/141.html 转摘请注明来源