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. dataTable.NET的column index的不同定義

    dataTable.NET是一個jQuery的plug in 第三方的library, 用來實現web page中table的interaction controls, 另外最近有在用的還有Teler ...

  2. [LeetCode] 20. Valid Parentheses 合法括号

    Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the inpu ...

  3. [LeetCode] 119. Pascal's Triangle II 杨辉三角 II

    Given an index k, return the kth row of the Pascal's triangle. For example, given k = 3,Return [1,3, ...

  4. [LeetCode] 136. Single Number 单独数

    Given a non-empty array of integers, every element appears twice except for one. Find that single on ...

  5. [LeetCode] 654. Maximum Binary Tree 最大二叉树

    Given an integer array with no duplicates. A maximum tree building on this array is defined as follo ...

  6. Eclipse安装Properties Editor插件

    安装步骤 1.打开eclispe编辑器help-->install new soft 2.输入软件地址 name:properties editor Location:http://proped ...

  7. url与uri区别

    url属性: 是要求按照url的写法来写地址 URL:Uniform Resource Locator 统一资源定位符.它是可以唯一标识一个资源的位置 写法: http://localhost:808 ...

  8. Windows中使用 Python 调用 Matlab 程序

    https://ww2.mathworks.cn/help/matlab/matlab_external/system-and-configuration-requirements.html http ...

  9. [Oracle] - 查看数据库中每个表占用空间大小,及进行表压缩

    查询用户创建的表 select * from user_tab_comments; -- 查询本用户的表,视图等. select * from user_col_comments; -- 查询本用户的 ...

  10. Docker部署ELK 7.0.1集群之Elasticsearch安装介绍

    elk介绍这里不再赘述,本系列教程多以实战干货为主,关于elk工作原理介绍,详情查看官方文档. 一.环境规划 主机名 IP 角色 节点名 centos01 10.10.0.10 es node-10 ...