xml.etree.ElementTree模块

一、xml综述

      xml和json的功能一样,虽然目前多家机构已经不再使用xml文件,但是仍有小部分的机构还在使用xml处理文件数据;此处简单介绍一下Python中是如何处理xml文件的;以便工作中使用的到。

二、xml文件读取

xml原文件内容

 1 <?xml version="1.0"?>
 2 <data>
 3     <country name="Liechtenstein">
 4         <rank updated="yes">2</rank>
 5         <year>2008</year>
 6         <gdppc>141100</gdppc>
 7         <neighbor name="Austria" direction="E"/>
 8         <neighbor name="Switzerland" direction="W"/>
 9     </country>
10     <country name="Singapore">
11         <rank updated="yes">5</rank>
12         <year>2011</year>
13         <gdppc>59900</gdppc>
14         <neighbor name="Malaysia" direction="N"/>
15     </country>
16     <country name="Panama">
17         <rank updated="yes">69</rank>
18         <year>2011</year>
19         <gdppc>13600</gdppc>
20         <neighbor name="Costa Rica" direction="W"/>
21         <neighbor name="Colombia" direction="E"/>
22     </country>
23 </data>

处理文件的代码

1 import  xml.etree.ElementTree as ET
2 
3 tree=ET.parse("file.xml")
4 root=tree.getroot()
5 print(root.tag)
6 for child in root:
7     print(child.tag,child.attrib)
8     for i in child:
9         print(i.tag,i.text,i.attrib)

三、

posted @ 2016-12-23 10:50  dudujing  阅读(56)  评论(0编辑  收藏  举报