加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

解析gbk格式带中文的xml

发布时间:2020-12-16 23:47:37 所属栏目:百科 来源:网络整理
导读:方案 ? ? ? ?1、以gbk格式读取xml文件为字符串,替换xml声明为utf-8格式 ? ? ? ?2、将字符串编码成utf-8格式,直接解析 ? 代码 1 def parse_xml_node(node): 2 if len(node.getchildren()) == 0: 3 return node.text if node.text is not None else ‘‘ 4 e

方案

? ? ? ?1、以gbk格式读取xml文件为字符串,替换xml声明为utf-8格式

? ? ? ?2、将字符串编码成utf-8格式,直接解析

?

代码

 1 def parse_xml_node(node):
 2     if len(node.getchildren()) == 0:
 3         return node.text if node.text is not None else ‘‘
 4     else:
 5         node_dict = {}
 6         for child in node.getchildren():
 7             if child.tag in node_dict.keys():
 8                 if not isinstance(node_dict[child.tag],list):
 9                     node_dict[child.tag] = [node_dict[child.tag]]
10                 node_dict[child.tag].append(parse_xml_node(child))
11             else:
12                 node_dict[child.tag] = parse_xml_node(child)
13         return node_dict
14 
15 def parse_gbk_xml(filename):
16     import codecs
17     from xml.etree import ElementTree
18     with codecs.open(filename,r,encoding=gbk) as fp:
19         text = fp.read().replace(<?xml version="1.0" encoding="GBK"?>,<?xml version="1.0" encoding="UTF-8"?>)
20     xdata = {}
21     element = ElementTree.fromstring(text.encode(utf-8))
22     xdata[element.tag] = parse_xml_node(element)

?

结果验证:

 1 # 文本内容
 2 <?xml version="1.0" encoding="GBK"?>
 3     <root>
 4         <head>
 5             <code>1</code>
 6             <message>正确</message>
 7             <value>320202</value>
 8         </head>
 9     </root>
10 
11 
12 # 解析结果
13 {root: {head: {message: uu6b63u786e,code: 1,value: 320202}}}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读