在当前目录下有一个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
--------------------
正文完