__author__ = "Alex Li"
import xml.etree.ElementTree as ET
tree = ET.parse("xmltest.xml")
root = tree.getroot()
print(root)
print(root.tag)
# 遍历xml文档
# for child in root:
# print(child.tag, child.attrib)
# for i in child:
# print(i.tag, i.text,i.attrib)
# for j in i:
# print(j.tag, j.text)
# 只遍历year 节点
for node in root.iter('year'):
print(node.tag, node.text)
for node in root.iter('population'):
print(node.tag, node.text)
xmltest.xml
<data>
<country name="Liechtenstein">
<rank updated="yes">2</rank>
<year updated_by="Alex">2011</year>
<gdppc>141100</gdppc>
<neighbor direction="E" name="Austria" />
<neighbor direction="W" name="Switzerland" />
</country>
<country name="Singapore">
<rank updated="yes">5</rank>
<year updated_by="Alex">2014</year>
<gdppc>59900</gdppc>
<neighbor direction="N" name="Malaysia" />
</country>
<country name="Panama">
<rank updated="yes">69</rank>
<year updated_by="Alex">2014</year>
<gdppc>13600</gdppc>
<neighbor direction="W" name="Costa Rica" />
<neighbor direction="E" name="Colombia" />
<info direction="W" name="Costa Rica">
<population>8</population>
<size>960</size>
</info>
</country>
</data>