python中ElementTree解析XML文件策略

<?xml version="1.0"?>
<data>
<country name="Liechtenstein">
<rank>1</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor name="Austria" direction="E"/>
<neighbor name="Switzerland" direction="W"/>
</country>
<country name="Singapore">
<rank>4</rank>
<year>2011</year>
<gdppc>59900</gdppc>
<neighbor name="Malaysia" direction="N"/>
</country>
<country name="Panama">
<rank>68</rank>
<year>2011</year>
<gdppc>13600</gdppc>
<neighbor name="Costa Rica" direction="W"/>
<neighbor name="Colombia" direction="E"/>
</country>
</data>

xml文件country_data.xml


 

#导入模块的方式

>>> import xml.etree.ElementTree as ET

#解析XML文件
>>> tree=ET.parse("country_data.xml")

#得到root节点

>>> root=tree.getroot()

#root节点的内容
>>> root.tag
'data'

#root节点的属性
>>> root.attrib
{}


 XML的查询方法

#使用root.iter遍历子元素

>>> for neighbor in root.iter("neighbor"):
... print(neighbor.attrib)
...
{'direction': 'E', 'name': 'Austria'}
{'direction': 'W', 'name': 'Switzerland'}
{'direction': 'N', 'name': 'Malaysia'}
{'direction': 'W', 'name': 'Costa Rica'}
{'direction': 'E', 'name': 'Colombia'}

猜你喜欢

转载自www.cnblogs.com/gaoyuxia/p/10551937.html