python3读取xml文件_Python3处理XML格式的数据

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值