在files目錄中有一個products.xml文件祭隔,要求讀取該文件中products節(jié)點所有子節(jié)點的值及子節(jié)點的屬性值
讀取products.xml文件
- 使用parse蠢终,導入模塊xml.etree.ElementTree
from xml.etree.ElementTree import parse
doc = parse('C:\\PyTest\\Selenium_OpenSchools\\test_selenium\\03-數(shù)據(jù)存儲\\files\\products.xml')
讀取xml文件中的每一個元素
- 使用for 循環(huán)一條條的讀取值
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('-'*10)
以下是完整的讀取xml文件節(jié)點的代碼
from xml.etree.ElementTree import parse
doc = parse('C:\\PyTest\\Selenium_OpenSchools\\test_selenium\\03-數(shù)據(jù)存儲\\files\\products.xml')
print(type(doc))
for item in doc.iterfind('products/product'): #迭代讀取xml文件中的每個節(jié)點值
id = item.findtext('id') #輸出id屬性
name = item.findtext('name') #輸出name屬性
price = item.findtext('price') #輸出price屬性
uuid = item.get('uuid') #輸出uuid屬性
print('uuid=',uuid)
print('id=',id)
print('name=',name)
print('price=',price)
print('-'*10)
讀取XML數(shù)據(jù)及節(jié)點.png
將products.xml文件內(nèi)容附上
<root>
<products>
<product uuid = '1234'>
<id>10000</id>
<name>iPhone9</name>
<price>9999</price>
</product>
<product uuid = '4321'>
<id>20000</id>
<name>mate20</name>
<price>5555</price>
</product>
<product uuid = '5678'>
<id>30000</id>
<name>mateX</name>
<price>3099</price>
</product>
</products>
</root>
總結
1.通過parse函數(shù)可以讀取xml文檔程奠,該函數(shù)返回ElementTree類型的對象
2.通過返回對象的iterfind方法可以對xml文件中的節(jié)點進行迭代讀取