Python数据存储之XML文档和字典的互转
作者:? 时间:2023-02-12 08:56:11
考点:
将字典转换为XML文档;
将XML文档转换为字典。
面试题
1.面试题一:如何将一个字典转换为XML文档,并将该XML文档保存为文本文件。
2.面试题二:如何读取XML文件的内容,并将其转换为字典。
解析
如何将一个字典转换为XML文档,并将该XML文档保存为文本文件:
这里需要用到第三方库:dicttoxml。需要安装一下
# coding=utf-8
import dicttoxml
from xml.dom.minidom import parseString
d = [20, 'name', {'name':'xiaohong', 'age':30, 'salary':500},
{'name':'honghong', 'age':34, 'salary':2050},
{'name':'lihua', 'age':10, 'salary':1200},
]
bxml = dicttoxml.dicttoxml(d, custom_root='persons') # 注意:此时返回值是二进制类型,所以需要解码哦~
xml = bxml.decode('utf-8')
print(xml)
print("---"*25)
# 美观格式
dom = parseString(xml)
prettyxml = dom.toprettyxml(indent=' ')
print(prettyxml)
# 保存
with open('persons1.xml', 'w', encoding='utf-8') as f:
f.write(prettyxml)
面试题二 之 如何读取XML文件的内容,并将其转换为字典:
这里需要用到第三方库:xmltodict。需要安装一下哦~
供我们读取的XML文件是products.xml,文件内容如下:
<!-- products.xml -->
<root>
<products>
<product uuid='1234'>
<id>10000</id>
<name>苹果</name>
<price>99999</price>
</product>
<product uuid='1235'>
<id>10001</id>
<name>小米</name>
<price>999</price>
</product>
<product uuid='1236'>
<id>10002</id>
<name>华为</name>
<price>9999</price>
</product>
</products>
</root>
# coding=utf-8
import xmltodict
with open('products.xml', 'rt', encoding='utf-8') as f:
xml = f.read()
d = xmltodict.parse(xml)
print(d)
print("---" * 25)
print(type(d)) # 输出为:<class 'collections.OrderedDict'>
# 说明此时已经转为字典(排序字典)~
print("---"*25)
# 美观格式
import pprint
dd = pprint.PrettyPrinter(indent=4)
dd.pprint(d)
dicttoxml用于将字典转换为XML文档;
xmltodict用于将XML文档转换为字典。
来源:https://juejin.cn/post/7102432915728007199
标签:Python,XML,文档,字典,互转
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
基于Python编写一个简单的垃圾邮件分类器
2022-02-26 08:11:23
Python文件夹批处理操作代码实例
2022-12-15 12:58:55
![](https://img.aspxhome.com/file/2023/4/112514_0s.png)
ORACLE8的分区管理
2010-07-30 13:18:00
Python基础之高级变量类型实例详解
2021-11-09 11:07:40
![](https://img.aspxhome.com/file/2023/0/112010_0s.png)
在IE 浏览器中使用 jquery的fadeIn() 效果 英文字符字体加粗
2011-06-06 10:28:00
怎么用Python识别手势数字
2021-11-14 16:35:35
![](https://img.aspxhome.com/file/2023/1/88901_0s.png)
小结Python的反射机制
2023-10-16 22:30:28
总结分析python数据化运营关联规则
2021-06-07 22:22:05
![](https://img.aspxhome.com/file/2023/1/135221_0s.png)
python交易记录链的实现过程详解
2022-09-01 19:44:46
![](https://img.aspxhome.com/file/2023/6/90656_0s.png)
SQL Server中的文件和文件组介绍
2024-01-14 06:57:45
![](https://img.aspxhome.com/file/2023/3/88243_0s.jpg)
sqlserver 数据库学习笔记
2024-01-14 21:54:33
Mysql按条件计数多种实现方法详解
2024-01-18 09:43:35
SQL 统计一个数据库中所有表记录的数量
2012-01-29 18:21:36
Python当中的array数组对象实例详解
2022-02-12 23:22:47
![](https://img.aspxhome.com/file/2023/8/81708_0s.png)
sqlserver中根据字符分割字符串的最好的写法分享
2012-06-06 19:44:40
Python入门教程(十)Python布尔值介绍
2022-06-01 18:01:55
![](https://img.aspxhome.com/file/2023/1/81521_0s.png)
推荐几款MySQL相关工具
2024-01-23 10:42:12
![](https://img.aspxhome.com/file/2023/9/116789_0s.png)
Discuz!NT 论坛整合ASP程序论坛教程
2011-03-31 11:09:00
原生Java操作mysql数据库过程解析
2023-07-19 23:27:57
![](https://img.aspxhome.com/file/2023/0/64110_0s.png)
思考如何提高交互设计水平?
2009-12-08 12:18:00