发现python上有关xml的实现方法还是蛮多的,第三方的框架也不少,但是其中没有像dom4j那样名声响亮的框架。所以,还是中规中居地介绍python的故有方法吧。
今天,先介绍一个ElementTree,看着还顺眼些。详细说明在代码注释中,结果在后面。
#coding:utf-8
'''
Created on 2015年1月12日
@author: neil
'''
from xml.etree import ElementTree
#xml内容以文件形式传入
#filepath=''
# with open(filepath,'rt') as f:
# tree=ElementTree.parse(f)
#xml内容以字符串形式传入
tree=ElementTree.fromstring('''<?xml version="1.0" encoding="utf-8"?>
4尾巴
Python测试ZopeJJJsdfsdfsdfs
''')
for node in tree.iter():#深度搜索、树的先序遍历
print type(node)
print 'tag:',node.tag#元素标签名
print 'tail:',node.tail#后面的字符串,多半是回车换行。根结点的结束标签后面文档结束,所以是None。
print 'attrib:',node.attrib#字典类型,字典的项对应元素属性,字典的键对应属性名称,字典的值对应属性值
print 'attrib-id-default:',node.attrib.get('id','NULL')#字典方法,按键取值,如果键不存在,就取默认值。默认值由第二个参数规定。
print 'attrib-id:',node.attrib.get('id')#字典方法,按键取值,如果键不存在,就取None,不会报错。
print 'attrib.items:',node.attrib.items()#二元元组的列表,列表的每一个项是一个二元元组,元组的前一个值是xml元素属性的名称,后一个值是属性的值。
print 'attrib.keys:',node.attrib.keys()#以列表的形式列举元素的所有属性名称
print 'find-caption:',node.find('caption')#只在该结点的所有子节点中选择符合元素名称的第一个子节点
print 'find-item:',node.find('item')
print 'findall:',node.findall('caption')#只在该结点的所有子节点中选择符合元素名称的所有子节点,范围类型为列表
print 'findtext-caption:',node.findtext('caption')#只在该结点的所有子节点中选择符合元素内容的第一个子节点
print 'getchildren:',node.getchildren() #所有子节点以列表形式给出
print 'iter:',node.iter()
for n in node.iter():#深度搜索、树的先序遍历该结点下的子树
print '++++',n.tag
print '- - - - - - - - - - - - - - - - '
输出结果如下:
tag: catalog
tail: None
attrib: {}
attrib-id-default: NULL
attrib-id: None
attrib.items: []
attrib.keys: []
find-caption: None
find-item:
findall: []
findtext-caption: None
getchildren: [, , , ]
iter:
++++ catalog
++++ maxid
++++ login
++++ caption
++++ item
++++ caption
++++ item