解析简单xml文档

Posted miss_林

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了解析简单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元素

 

以上是关于解析简单xml文档的主要内容,如果未能解决你的问题,请参考以下文章

HTML文档JS解析库介绍

解析简单xml文档

在java中解析xml有哪几种方法

Android解析XML文档的两种方式的简单对比

Android之DOM解析XML

Android之DOM解析XML