from basic_config_vars.config_vars import moviesAllFilePath,moviesFilePath  #自定义的一些文件变量
import xmltodict
import json
import os
import traceback class XmlDict():
def __init__(self):
pass #初始化数据,传入参数1、xml文件路径 2、xml格式字符串 3、json字符串 4、dict字典
def init_data(self,file_Str_Dict):
if isinstance(file_Str_Dict,str) and os.path.isfile(file_Str_Dict):
with open(file_Str_Dict) as fp:
self.data=fp.read()
elif isinstance(file_Str_Dict,(str,dict)):
self.data=file_Str_Dict def xml_to_dict(self,file_Str_Dict):
self.init_data(file_Str_Dict) data_orderedD=xmltodict.parse(self.data)
data_json=json.dumps(data_orderedD,indent=4)
data_dict=json.loads(data_json) return data_dict def dicttoxml(self,file_Str_Dict):
self.init_data(file_Str_Dict)
if isinstance(self.data,str):
try:
self.data=json.loads(self.data)
except:
print('传入参数非json或dict类型,无法转换。')
traceback.print_exc()
return None
return xmltodict.unparse(self.data,pretty=True,encoding='gb2312') if __name__=='__main__':
#obj=XmlDict(moviesFilePath) obj = XmlDict()
d=obj.xml_to_dict(moviesAllFilePath)
print(d)
print('*'*30)
#print(obj.dicttoxml(json.dumps(d)))
print(obj.dicttoxml('{"nihao":{"ty":"leixing","fuoran":"feichang"}}'))
print('hahaha')

XMl文件参考:

<collection shelf="New Arrivals">
<movie title="Enemy Behind">
<type>War, Thriller</type>
<format>DVD</format>
<year>2003</year>
<rating>PG</rating>
<stars>10</stars>
<description>Talk about a US-Japan war</description>
</movie>
<movie title="Transformers">
<type>Anime, Science Fiction</type>
<format>DVD</format>
<year>1989</year>
<rating>R</rating>
<stars>8</stars>
<description>A schientific fiction</description>
</movie>
<movie title="Trigun">
<type>Anime, Action</type>
<format>DVD</format>
<episodes>4</episodes>
<rating>PG</rating>
<stars>10</stars>
<description>Vash the Stampede!</description>
</movie>
<movie title="Ishtar">
<type>Comedy</type>
<format>VHS</format>
<rating>PG</rating>
<stars>2</stars>
<description>Viewable boredom</description>
</movie>
</collection>

python3 xml_to_dict、dict_to_xml等互相转换的方法的更多相关文章

  1. 微信录音文件上传到服务器以及amr转化成MP3格式,linux上转换简单方法

    微信公众号音频接口开发 根据业务需求,我们可能需要将微信录音保存到服务器,而通过微信上传语音接口上传到微信服务器的语音文件的有效期只有3天,所以需要将文件下载到我们自己的服务器. 上传语音接口 wx. ...

  2. C#中二进制、十进制和十六进制互相转换的方法

    二进制在C#中无法直接表示,我们一般用0和1的字符串来表示一个数的二进制形式.比如4的二进制为"100".下面介绍C#里面用于进制转换的方法. 十进制转换为二进制(int--> ...

  3. jquery对象与dom对象之间互相转换的方法

    本文主要讲述jquery对象和js里的dom对象之间互相转换的方法,使jquery对象可以直接使用js里的方法,或js里的dom对象使用jquery里的方法. jquery对象和dom对象是不一样的, ...

  4. 托管和非托管转换新方法:Marshaling Library(zz) 【转】

    托管和非托管转换新方法:Marshaling Library(zz) 托管和非托管转换新方法:Marshaling Library(zz) http://hi.baidu.com/superql/bl ...

  5. 【ABAP系列】SAP ABAP 行列转换的方法

    公众号:SAP Technical 本文作者:matinal 原文出处:http://www.cnblogs.com/SAPmatinal/ 原文链接:[ABAP系列]SAP ABAP 行列转换的方法 ...

  6. 【转】在Python的struct模块中进行数据格式转换的方法

    这篇文章主要介绍了在Python的struct模块中进行数据格式转换的方法,文中还给出了C语言和Python语言的数据类型比较,需要的朋友可以参考下 Python是一门非常简洁的语言,对于数据类型的表 ...

  7. python3.6中 字典类型和字符串类型互相转换的方法

    mydic = {"俄罗斯": {"1":"圣彼得堡", "2":"叶卡捷琳堡", "3& ...

  8. python3 中encode 和decode的使用方法。

    编码: 将文本转换成字节流的过程.即Unicode----------->特定格式的编码方式,产生特定的字节流保存在硬盘中(一般为utf-8格式). 解码: 将硬盘中的字节流转换成文本的过程.即 ...

  9. 使用js进行string和json之间转换的方法

    在数据传输过种中,json是以文本,即字符串的形式传递,字符串形似Json对象: var str1 = '{ "name": "Amy", "sex& ...

随机推荐

  1. [LeetCode] 141. Linked List Cycle 链表中的环

    Given a linked list, determine if it has a cycle in it. Follow up:Can you solve it without using ext ...

  2. CentOS的vsftp修改默认配置路径方法

    修改ftp的根目录只要修改/etc/vsftpd/vsftpd.conf文件即可: 加入如下几行: local_root=/var/www/htmlchroot_local_user=YESanon_ ...

  3. 【VS开发】MFC滑动条 CSliderCtrl

    在MFC中滑动条(CSliderCtrl)是个常用的控件,用法如下: 主要要方法有: 1.设置.取得滑动范围: void SetRange( int nMin, int nMax, BOOL bRed ...

  4. React+antd+less框架搭建步骤,看吧,整的明白儿的

    1.node版本 首先你要先看下你的node版本,如果小于10,建议升级到10及以上,因为低版本的 node 在自动创建 react框架时,有配置文件跟10及以上的有比较大的差异,而且需要增加.修改的 ...

  5. LeetCode 653. 两数之和 IV - 输入 BST(Two Sum IV - Input is a BST)

    653. 两数之和 IV - 输入 BST 653. Two Sum IV - Input is a BST 题目描述 给定一个二叉搜索树和一个目标结果,如果 BST 中存在两个元素且它们的和等于给定 ...

  6. Get Docker Engine - Community for Ubuntu

    Get Docker Engine - Community for Ubuntu Uninstall old versions$ sudo apt-get remove docker docker-e ...

  7. JavaScript进行UTF-8编码与解码

    JavaScript本身可通过charCodeAt方法得到一个字符的Unicode编码,并通过fromCharCode方法将Unicode编码转换成对应字符. 但charCodeAt方法得到的应该是一 ...

  8. spark 预编译安装

    1.下载地址: http://mirrors.tuna.tsinghua.edu.cn/apache/spark/spark-3.0.0-preview/spark-3.0.0-preview-bin ...

  9. fastjson框架如何处理boolean?CURRENT_TIMESTAMP使用报错?什么是 ONLINE DDL 及 pt-online-schema-change ? getBytes引起的乱码问题?

    一.使用fastjson框架进行序列化时,若莫个参数为Boolean类型,而json里的值是其它类型时,框架如何处理? 1.true, false,正常赋值2.int类型,若为1,则为true,否则为 ...

  10. UOJ269 清华集训2016 如何优雅地求和 下降幂多项式、NTT

    代码 神仙题? 看到连续的点值,那么一定是要利用到连续点值的性质,可以考虑下降幂多项式,即考虑多项式\(F(x) = \sum\limits_{i=0}^m a_ix^{\underline i}\) ...