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

python编程中常用的12种基础知识总结

python编程中常用的12种基础知识总结:正则表达式替换,遍历目录方法,列表按列排序、去重,字典排序,字典、列表、字符串互转,时间对象操作,命令行参数解析(getopt),print 格式化输出,进制转换,Python调用系统命令或者脚本,Python 读写文件。...

SAE+python+Tornado+pyTenjin 的完整示例

python 简单易懂,Tornado 高效易学,pyTenjin 轻巧快速,SAE 安全稳定使用门槛低。现在把他们结合在一起做了一个可运行在SAE 上的完整示例。...

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

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

Leave a Comment