Python学习-ElementTree 方法读取XML

来源:互联网 发布:法比奥奥奥 知乎 编辑:程序博客网 时间:2024/05/15 02:18

要想解析XML需分两步:

第一步: 加载XML文件
    1) 加载指定字符串
    2) 加载指定文件

第二步: 获取节点的方法
    1) 通过 getiterator
    2) 通过 getchildren
    3) find 方法
    4) findall 方法


#coding=GBKfrom xml.etree import ElementTree as ETdef print_node(node):    print "=============================================="      print "node.attrib:%s" % node.attrib      print "node.tag:%s" % node.tag      print "node.text:%s" % node.text      if node.attrib.has_key("name"):          print "node.attrib['rank']:%s" % node.attrib['name']  if __name__ == '__main__':#第一步:  加载XML文件    #1.从变量读取,参数为XML段,返回的是一个根Element对象    root = ET.fromstring(open("test.xml").read())    print (type(root)) #打印结果: <class 'xml.etree.ElementTree.Element'>        #2.从xml文件中读取,用getroot获取根节点,根节点也是Element对象    tree = ET.parse(r'test.xml')    root2 = tree.getroot()    print (type(root2)) #打印结果: <class 'xml.etree.ElementTree.Element'>    #第二步: 获取节点的方法    # 1.通过getiterator       print('1.通过getiterator  ')    first_node = root.getiterator("country")      for node in first_node:          print_node(node)      #获取指定某个节点(这里是"country") 个数    print first_node.__len__()        # 2.通过 getchildren获取指定某个节点的子节点    print ('2.通过 getchildren获取指定某个节点的子节点')    first_node_child = first_node[0].getchildren()[0]      print_node(first_node_child)    print first_node[0].getchildren()[1], first_node[0].getchildren()[1].tag              # 3.find方法 ,返回第一个找到的节点     print ('3.find方法,返回第一个找到的节点  ')    node_find = root.find('country2')      print node_find, node_find.attrib, '=='    print_node(node_find)            # 4.findall方法      print ('4.findall方法,返回一个所有找到的节点的元组   ')    node_findall = root.findall("country/rank")      print node_findall


test.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>    <country2 name="Test">        <rank>234</rank>        <year>2016</year>        <gdppc>346344</gdppc>        <neighbor name="Costa Rica" direction="W"/>        <neighbor name="Colombia" direction="E"/>    </country2>    </data>


原创粉丝点击