xml.etree.elementtree
上一篇 /
下一篇 2015-09-13 20:45:37
/ 个人分类:python
#!/usr/bin/env python
# -*- coding:utf8 -*-
try:
import xml.etree.cElementTree as et
except:
import xml.etree.ElementTree as et
strxml = """<?xml version="1.0"?>
<data>
<country name="Liechtenstein">
<rank>1</rank>
<year>2008</year>
<gdppc>141100</gdppc>
<neighbor name="Austria" direction="E"/>
<neighbor name="Switzerland" direction="W"/>
</country>
<country name="Singapore">
<rank>4</rank>
<year>2011</year>
<gdppc>59900</gdppc>
<neighbor name="Malaysia" direction="N"/>
</country>
<country name="Panama">
<rank>68</rank>
<year>2011</year>
<gdppc>13600</gdppc>
<neighbor name="Costa Rica" direction="W"/>
<neighbor name="Colombia" direction="E"/>
</country>
</data>"""
tree = et.fromstring(strxml) #这个返回值是一个element
print len(tree.getchildren()) #只获取当前节点下的子节点
print len(tree.findall('')) #只查找当前节点下的子节点,不查找子节点下的子节点
for x in tree.iter(): #可以循环遍历子节点下的子节点
print x.tag
for xx in tree.itertext(): #查找所有节点下的标签,包括当前节点下的子节点的子节点
if xx == '1':
print xx
收藏
举报
TAG: