用python解析xml的几种方法_python解析XML方法

python有三种方法解析XML,SAX,DOM,以及ElementTree不止各有利弊比如xml.dom.minidom方法。

权衡自己学习ElementTree和xml.dom.minidom。

XML语法看w3c,主要看xml的层数和复杂程度,数据量大小。

一:根据看的内容总结xml.dom.minidom方法简单应用:

主要用到 xml.dom.minidom中的parse和documentElement,xml.dom.minidom.parse('file.xml')打开,xml.dom.minidom.documentElement读xml

就是有一个abc.xml文件后,

import xml.dom.minidom

dom = xml.dom.minidom.parse('abc.xml')#打开xml文档

root =dom.documentElement#读取xml

使用技巧:

root.getElementsByTagName('caption') 获得的是标签为caption 一组标签,b[0]表示一组标签中的第一个;b[2] ,表示这一组标签中的第三个。

getAttribute方法可以获得元素的属性所对应的值。

firstChild 属性返回被选节点的第一个子节点,.data表示获取该节点人数据。二:.ElementTree(元素树)方法:

与上面的xml.dom.minidom比较而言更利于对复杂的xml进行遍历查找,而且他是轻量级,速度快,内存消耗小。

demo:

tianma

manager

xingkong

admin

#coding=utf-8

from xml.etree import ElementTree as ET

def print_node(node):

'''print node message'''

print "=============================================="

print "node.attrib:%s" % node.attrib

if node.attrib.has_key("age") > 0:

print "node.attrib['age']:%s" % node.attrib['age']

print "node.tag:%s" % node.tag

print "node.tag:%s" % node.text

def read_xml(text):

'''read xml file'''

# root = ET.parse(r"C:\Users\yshe\Desktop\testxml")

root = ET.fromstring(text)

#1 Go through getiterator method

lst_node = root.getiterator("person")

for node in lst_node:

print_node(node)

#2 Go througn getchildren method get subarea node

lst_node_child = lst_node[0].getchildren()[0]

print_node(lst_node_child)

#3 Go througn find method

node_find = root.find('person')

print_node(node_find)

#4 Go through findall method

node_findall = root.findall("person/name")[1]

print_node(node_findall)

if __name__ == '__main__':

read_xml(open("test.xml").read())

#coding=utf-8

from xml.etree import ElementTree as ET

#Find out all persons age

per=ET.parse('test.xml')

p=per.findall('person')

for x in p:

print x.attrib

print

for oneper in p:  #Find out person node

for child in oneper.getchildren(): #Find out person child node

print child.tag,':',child.text

print 'age:',oneper.get('age')

print "=============================================="

以上分别从不同帖子整理。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值