39 - 读取XML节点和属性值

在当前目录下有一个products.xml 文件,要求读取该文件中products节点的所有子节点的值以及子节点的属性值

<!-- products.xml -->
<root>
	<products>
		<product uuid="1234">
			<id>10000</id>
			<name>iphone9</name>
			<price>9999</price>
		</product>
			<product uuid="4321">
			<id>20000</id>
			<name>特斯拉</name>
			<price>800000</price>
		</product>
			<product uuid="5678">
			<id>30000</id>
			<name>Mac Pro</name>
			<price>40000</price>
		</product>
	</products>
</root>
from xml.etree.ElementTree import parse

doc = parse('products.xml')
print(type(doc))

for item in doc.iterfind('products/product'):
    id = item.findtext('id')
    name = item.findtext('name')
    price = item.findtext('price')
    uuid = item.get('uuid')
    print('uuid :', uuid)
    print('id :', id)
    print('name :', name)
    print('price :', price)
    print('-'*20)
<class 'xml.etree.ElementTree.ElementTree'>
uuid : 1234
id : 10000
name : iphone9
price : 9999
--------------------
uuid : 4321
id : 20000
name : 特斯拉
price : 800000
--------------------
uuid : 5678
id : 30000
name : Mac Pro
price : 40000
--------------------

40 - xml文档与字典之间的互相转换

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

若尘

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值