python xmltodict 解析xml gbk 编码问题解决

介绍 python xmltodict 解析xml gbk 编码问题的解决方法

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 转摘请注明来源

Suggested Topics

3行 Python 代码解简单的一元一次方程

一元一次方程:只含有一个未知数(即“元”),并且未知数的最高次数为1(即“次”)的整式方程叫做一元一次方程(英文名:`linear equation with one unknown`)。...

python SQLite 数据库提速经验

SQLite 特点是轻巧,依赖少,数据库就一个文件,打包即可提走。最近做一个应用,千万条数据,更新频繁,但处理方式很简单,首先直接用SQLite 处理,结果两分钟可以完成处理一次,这个还是太慢了。下面介绍 SQLite 优化提速的经验。...

Leave a Comment