Python的xmltodict库是一款专门用于处理XML数据的工具,它可以将XML字符串快速转换为Python字典,也能把字典反向转换为XML格式,避免了手动解析XML节点、属性的繁琐操作,在处理接口返回、配置文件等XML场景时非常实用。
xmltodict库的安装
xmltodict是第三方库,需要通过pip命令安装,在终端执行以下命令即可完成安装:
# 安装xmltodict库 pip install xmltodict
XML转字典的核心用法
使用xmltodict.parse()方法可以将XML字符串转换为Python字典,这是最常用的功能。下面通过几个常见场景来演示用法。
基础XML转换
对于简单的XML结构,转换后的字典会保留节点的层级关系,文本内容会存放在#text键中:
import xmltodict
# 定义简单XML字符串
xml_str = '''<user>
<name>张三</name>
<age>25</age>
<city>北京</city>
</user>'''
# 将XML转换为字典
result_dict = xmltodict.parse(xml_str)
print(result_dict)
# 输出结果:{'user': {'name': '张三', 'age': '25', 'city': '北京'}}
# 获取具体字段值
print(result_dict['user']['name']) # 输出:张三
带属性的XML转换
如果XML节点带有属性,属性会被转换为字典的子键,键名格式为@属性名:
import xmltodict
xml_with_attr = '''<book id="1001" category="编程">
<title>Python入门教程</title>
<price>59.9</price>
</book>'''
result = xmltodict.parse(xml_with_attr)
print(result)
# 输出结果:{'book': {'@id': '1001', '@category': '编程', 'title': 'Python入门教程', 'price': '59.9'}}
# 获取属性值
print(result['book']['@id']) # 输出:1001
处理列表结构的XML
当XML中存在多个同名的子节点时,默认会转换为列表:
import xmltodict
xml_list = '''<class>
<student>
<name>李四</name>
<score>90</score>
</student>
<student>
<name>王五</name>
<score>85</score>
</student>
</class>'''
result = xmltodict.parse(xml_list)
print(result)
# 输出结果:{'class': {'student': [{'name': '李四', 'score': '90'}, {'name': '王五', 'score': '85'}]}}
# 遍历学生列表
for student in result['class']['student']:
print(f"姓名:{student['name']},分数:{student['score']}")
字典转XML的核心用法
使用xmltodict.unparse()方法可以将Python字典转换为XML字符串,转换时会自动处理字典的层级结构,生成对应的XML节点。
基础字典转XML
对于简单的字典结构,转换后的XML会保留字典的键作为节点名:
import xmltodict
# 定义字典
data_dict = {
'user': {
'name': '赵六',
'age': '28',
'hobby': '跑步'
}
}
# 将字典转换为XML字符串
xml_result = xmltodict.unparse(data_dict, pretty=True)
print(xml_result)
上述代码的输出结果如下:
<?xml version="1.0" encoding="utf-8"?>
<user>
<name>赵六</name>
<age>28</age>
<hobby>跑步</hobby>
</user>
带属性的字典转XML
如果要生成带属性的XML,只需要在字典中按照@属性名的格式定义属性键即可:
import xmltodict
data_with_attr = {
'product': {
'@id': '2001',
'@status': '在售',
'name': '无线鼠标',
'price': '89.9'
}
}
xml_result = xmltodict.unparse(data_with_attr, pretty=True)
print(xml_result)
输出结果中product节点会带有id和status两个属性。
常见注意事项
- xmltodict转换后的所有值默认都是字符串类型,如果需要数值类型需要手动转换
- 当XML中存在空节点时,转换后的字典对应键的值为
None - 使用
unparse()方法时,如果不传入pretty参数,生成的XML会没有换行和缩进,默认是紧凑格式 - 处理大文件XML时,可以使用
xmltodict.parse()的stream模式,避免一次性加载全部内容占用过多内存
实际应用场景示例
假设我们需要调用一个返回XML格式的接口,获取用户列表数据并转换为字典处理:
import xmltodict
import requests
# 模拟请求返回XML数据(实际场景中替换为真实接口地址,如http://ipipp.com/api/user_list)
xml_response = '''<response>
<code>200</code>
<msg>成功</msg>
<data>
<user>
<id>1</id>
<name>张三</name>
</user>
<user>
<id>2</id>
<name>李四</name>
</user>
</data>
</response>'''
# 转换XML为字典
result = xmltodict.parse(xml_response)
if result['response']['code'] == '200':
user_list = result['response']['data']['user']
for user in user_list:
print(f"用户ID:{user['id']},用户名:{user['name']}")