<info> <person > <id>1</id> <name>fsy</name> <age >24</age> </person> <person> <id>2</id> <name>jianjian</name> <age>24</age> </person> <count id ='1'>1000</count> </info>
def read_xml(file): # parse()函数会返回一个能代表整篇文档的对象。这不是根元素。要获得根元素的引用可以调用getroot()方法。 tree = etree.parse(file) root = tree.getroot() return root
def print_node(node):
'''''打印结点基本信息'''
print("node.tag:%s" % node.tag)
print("node.attrib:%s"%node.attrib)
print( "node.text:%s" % node.text)
find_all
>>> root = read_xml ('first.xml')
>>> res = root.findall("person")
[<Element 'person' at 0x00000000033388B8>, <Element 'person' at 0x0000000003413D68>]
注意:findall只查询直接的子节点
>>> r1 = root.findall("id")
>>> r1
[]
>>> r =tree.findall(".//id")
>>> for e in r:
print( e,e.text)
<Element 'id' at 0x00000000034279F8> 1
<Element 'id' at 0x0000000003427B38> 2
#find()方法用来返回第一个匹配到的元素。当我们认为只会有一个匹配,或者有多个匹配但我们只关心第一个的时候,这个方法是很有用的。
>>> res[0].find("id")
<Element 'id' at 0x0000000003413CC8>
>>> print_node(res[0].find("id"))
node.tag:id
node.attrib:{}
node.text:1
>>> bk = res[0].find("no")
>>> bk
>>> type(bk)
<class 'NoneType'>
>>> res[0].find("id")
<Element 'id' at 0x0000000003413CC8>
>>> if res[0].find("id"):
print("find")
else:
print("not find")
not find
>>> if res[0].find("id") is not None:
print("find")
else:
print("not find")
find
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有