4.1读取xml中的节点及属性值
读取xml档中的节点
·
学习目标:
①:读取xml中的节点及属性值
- Python日常
内容展示:
①:读取xml中的节点及属性值
from xml.etree.ElementTree import parse # 导入库
doc = parse('files/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('---------')
编写一个名为product.xml文档,位置放在files中
<root>
<products>
<product uuid="1234">
<id>10000</id>
<name>iphone9</name>
<price>9999</price>
</product>
<product uuid="1254">
<id>20000</id>
<name>特斯拉</name>
<price>800000</price>
</product>
<product uuid="1574">
<id>30000</id>
<name>Mac pro</name>
<price>4000</price>
</product>
</products>
</root>
总结:
通过parse函数可以读取xml文档,该函数返回elementTree类型对象,通过该对象的iterfind方法可以对xml中特定的节点进行迭代
- CSDN Python日常 第【4】1 篇
- 下一篇链接
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐
所有评论(0)