python xmltodict 解析xml gbk 编码问题

pylist 764

python xmltodict 解析xml gbk 编码问题

ValueError: multi-byte encodings are not supported
# -*- 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')

输出:

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>
登录发表评论