python解析xml文件选用模块_python 模块- 对XML的解析 ElementTree(元素树)

参考地址:http://blog.csdn.net/yueguanghaidao/article/details/7265246

python的官方文档:https://docs.python.org/2/library/xml.etree.elementtree.html

前述,库文件说明:

Source code:Lib/xml/etree/ElementTree.py

导入的库文件为:from xml.etree import ElementTree

为了使用方便可以像命名别名方式:

from xml.etree import ElementTree as ET

理解:

element是个容器对象,有些属性:

1) 一个tag

2) 一些attrib,或者为空 {}

3) 一个text

4) 一些子element

它是介于list和dict的中间体容器。

find, findall 结果就是一个list( find和 findall的区别, find是查找第一tag对应的element下所有元素, findall是查找对应tag的所有elements)

root.attrib 结果就是一个dict

具体使用

下面是一个转载的例子:

test.xml如下:

1

2008

141100

4

2011

59900

68

2011

13600

1.加载xml文件

加载XML文件共有2种方法,一是加载指定字符串,二是加载指定文件

a) parse 加载xml文件

b) fromstring 加载指定字符串

2.获取element的方法

a) 通过getiterator

b) 过 getchildren

c) find方法

d) findall方法

通过例子学习下:

from xml.etree import ElementTree as ET

#coding=gbk

tree = ET.parse("test.xml")

root = tree.getroot()

print root.tag, root.attrib, root.text

for child in root:

print child.tag, child.attrib, root.text

#getiterator方法, 得到对应tag的所有elemnt的

countrys = root.getiterator("country")

for country in countrys:

print "===", country.tag, country.attrib

#得到root下的所有子元素

childs = root.getchildren()

for child in childs:

print "+++", child.tag, child.attrib

#find方法,查找对应tag的第一个elment下的elements,支持path

fchilds = root.find("country")

for fchild in fchilds:

print "---", fchild.tag, fchild.attrib

#findall方法,查找所有的对应tag的所有element, 支持path

fachilds = root.findall("country")

for fachild in fachilds:

print "---s", fachild.tag, fachild.attrib

fapchilds = root.findall("country/neighbor")

for fapchild in fapchilds:

print "---sp", fapchild.tag, fapchild.attrib

注意问题:

中文编码问题,ElementTree只支持 utf8编码

所以当时gbk编码的时候,需要转码。

字符串转码:str.decode('gbk').encode('utf8'), 并且xml的头文件encoding为gbk的需要修改,如:

则需要str=str.replace('GBK', 'utf-8')

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值