解析简单xml文档

一、解析简单的xml文档

使用xml.etree.ElementTree 下的parse()

xmlName.xml的文档的内容如下:

<?xml version="1.0"?>
<data>
    <country name="zhongguo">
        <rank updated="yes">2</rank>
        <year >2017</year>
        <gdppc>14110</gdppc>
        <neighbor name="riben" direction="e"/>
        <neighbor name="hanguo" direction="w"/>
    </country>
     <country name="chaoxian">
        <rank updated="yes">3</rank>
        <year >2016</year>
        <gdppc>59900</gdppc>
        <neighbor name="zhongguo" direction="w"/>
        <neighbor name="hanguo" direction="e"/>
    </country>
     <country name="meiguo">
        <rank updated="yes">5</rank>
        <year >2009</year>
        <gdppc>13600</gdppc>
        <neighbor name="yingguo" direction="n"/>
        <neighbor name="deguo" direction="s"/>
    </country>
</data>

以下代码是对xmlName.xml文档的解析

from xml.etree.ElementTree import parse

with open('xmlName.xml') as f:
    et = parse(f)
    root = et.getroot()
    print root
    print root.tag
    print root.attrib
    print root.text
    print root.text.strip()
    # child = root.getchildren() 将被去掉
    for child in root:
        print child.get('name')

    '''下面的三个用只能找到根元素的直接子元素'''
    root.find('country')
    root.findall('country')
    root.iterfind('country')

    '''可以找到任意元素'''
    print list(root.iter())
    print list(root.iter('rank'))

    '''findall()的高级用法'''
    root.findall('country/*') #coutry元素下的所有子元素,/*
    root.findall('.//rank') #所有rank元素,.//
    root.findall('.//rank/..') #所有rank元素的父元素, /..

    root.findall('country[@name]') #有name属性的coutry元素,@attrib
    root.findall('country[@name="chaoxian"]') #name属性等于"chaoxian"的coutry元素,@attrib="value"

    root.findall('country[rank]') #子元素有rank元素的country元素,tag
    root.findall('country[rank="1"]') #子元素有rank="1"的country元素,tag=text

    root.findall('country[1]') #索引为1的country元素,根据位置查找
    root.findall('country[last()]') #最后一个country元素
    root.findall('country[last()-1]') #倒数第二个country元素

 

posted on 2017-04-12 22:16  miss_林  阅读(166)  评论(0编辑  收藏  举报

导航