python:xml模块用法-xml处理

xmltest.xml内容如下:
<data>
<country name="Liechten">
<rank updated="yes">1</rank>
<year updated_by="Alex">2017</year>
<gdppc>140000</gdppc>
<neighbor direction="E" name="Austria" />
<neighbor direction="W" name="Switzerland" />
</country>
</data>



xml处理:
import xml.tree.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)

#只遍历year节点
for node in root.iter('year')
......print(node.tag,node.text)

猜你喜欢

转载自blog.51cto.com/3906249/2152682