码迷,mamicode.com
首页 > 编程语言 > 详细

python解析XML之ElementTree

时间:2016-05-11 01:08:14      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:

#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>

 

python解析XML之ElementTree

标签:

原文地址:http://www.cnblogs.com/flintlovesam/p/5479953.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!