标签:
#coding=utf-8 from xml.etree import ElementTree as ET tree=ET.parse(‘test.xml‘) root = tree.getroot() #p=per.findall(‘caption‘) #for oneper in p: # for child in oneper.getchildren(): # print child.tag,‘:‘,child.text #for node in root.findall(‘caption‘): # print node.tag pe=root.findall(‘./item‘) first = 0 second = 0 third = 0 for child in pe: # for child in oneitem.getchildren(): print "the first layer-------------" print child.tag,‘tag:‘,child.text,‘attr:‘ ,child.attrib second_child=child.findall(‘./item‘) first+=1 for thirdchild in second_child: print "the second layer==========" gchild=thirdchild.findall(‘./item‘) print thirdchild.tag,‘tag:‘,thirdchild.text,‘attr:‘ ,thirdchild.attrib second+=1 # print gchild.tag,‘-88-:‘,gchild.text # print type(gchild) for i in gchild: print "the third layer 3333333333" print "i in child %s"%i print i.tag,‘-5656-:‘,i.text,‘attr:‘ ,i.attrib third+=1 print "first =%d\n"%first print "second=%d\n"%second print "third =%d\n"%third
<?xml version="1.0" encoding="utf-8"?> <catalog> <service>4</service> <item id="1"> <item id="11"> <caption>c1</caption> <caption>c2</caption> <caption>c3</caption> </item> </item> <item id="9"> <item id="99"> <item id="999"> </item> </item> </item> <item id="8"> <item id="88"> <item id="888"> </item> </item> </item> <item id="2"> <caption> </caption> </item> <item id="3"> <caption> <item>itemc4</item> <book>Zope2</book> </caption> </item> <item id="4"> <caption>c5</caption> </item> <item id="5"> <caption>c6</caption> <caption>c7</caption> </item> <item>item6</item> <item>item7</item> </catalog>
标签:
原文地址:http://www.cnblogs.com/flintlovesam/p/5479953.html