码迷,mamicode.com
首页 > 其他好文 > 详细

解析简单xml文档

时间:2017-04-12 23:11:01      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:open   code   元素   位置   cti   cout   span   direct   etc   

一、解析简单的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元素

 

解析简单xml文档

标签:open   code   元素   位置   cti   cout   span   direct   etc   

原文地址:http://www.cnblogs.com/misslin/p/6693223.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!