book_find=root.find('list')
for note in book_find:
print note.tag+':'+note.text
运行结果:
head:bookone
name:python check
number:001
page:200
findall方法将找到指定的所有节点:
# -*- coding: cp936 -*-
#@小五义
import xml.etree.ElementTree
root=xml.etree.ElementTree.parse('book.xml')
book=root.findall('list')
for book_list in book:
for note in book_list:
print note.tag+':'+note.text
运行结果:
head:bookone
name:python check
number:001
page:200
head:booktwo
name:python learn
number:002
page:300
3、对book.xml进行解析的实例
# -*- coding: cp936 -*-
#@小五义
import xml.etree.ElementTree
root=xml.etree.ElementTree.parse('book.xml')
book=root.findall('list')
for book_list in book:
print '='*20
if book_list.attrib.has_key('id'):
print "id:"+book_list.attrib['id']
for note in book_list:
print note.tag+':'+note.text
print '='*20
运行结果为:
====================
id:001
head:bookone
name:python check
number:001
page:200
====================
id:002
head:booktwo
name:python learn
number:002
page:300
====================
注意:
当要获取属性值时,如list id='001',用attrib方法。
当要获取节点值时,如<head>bookone</head>中的bookone用text方法。
当要获取节点名时,用tag方法。










