XML文件内容如下:
10000
iPhone9
9999
20000
特斯拉
800000
30000
Mac Pro
40000
读取与搜索XML文件
from xml.etree.ElementTree import parse
doc = parse('products.xml')
# 通过XPath搜索子节点集合,然后对子节点集合进行遍历
for item in doc.iterfind('products/product'):
id = item.findtext('id') # 读取product节点的id子节点的值
name = item.findtext('name') # 读取product节点的name子节点的值
price = item.findtext('price')
print('uuid =', item.get('uuid')) # 读取product节点的uuid属性的值
print('id =', id)
print('name =', name)
print('price =', price)
print('----------------------')
输出结果:
uuid = 1234
id = 10000
name = iPhone9
price = 9999
----------------------
uuid = 4321
id = 20000
name = 特斯拉
price = 800000
----------------------
uuid = 5678
id = 30000
name = Mac Pro
price = 40000
----------------------
字典转换为XML字符串
将字典转换为XML文件需要使用 dicttoxml模块 中的 dicttoxml 函数,使用 pip 命令安装该模块:pip install dicttoxml
用例:
import dicttoxml
from xml.dom.minidom import parseString
import os
# 定义一个列表
d = [20, 'names',
{'name': 'Bill', 'age': 30, 'salary': 2000},
{'name': 'Jack', 'age': 34, 'salary': 3000},
{'name': 'John', 'age': 25, 'salary': 2500}]
# 转换为XML格式(bytes形式)
bxml = dicttoxml.dicttoxml(d, custom_root='persons')
xml = bxml.decode('utf-8')
print(xml)
# 解析XML字符串
dom = parseString(xml)
# 生成带缩进格式的XML字符串
prettyxml = dom.toprettyxml(indent=' ')
# 写入文件
f = open('persons.xml', 'w')
f.write(prettyxml)
f.close()
转换后的XML文件内容:
20
names
Bill
30
2000
Jack
34
3000
John
25
2500