python xml解析实例详解

yipeiwu_com5年前Python基础

python xml解析

first.xml 

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

from xml.etree import ElementTree as etree 

读入

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:



#find()方法用来返回第一个匹配到的元素。当我们认为只会有一个匹配,或者有多个匹配但我们只关心第一个的时候,这个方法是很有用的。 
>>> res[0].find("id") 
<Element 'id' at 0x0000000003413CC8> 
>>> print_node(res[0].find("id")) 
node.tag:id 
node.attrib:{} 
node.text:1 

find查找失败:

使用find要注意在布尔上下文中,如果ElementTree元素对象不包含子元素,其值则会被认为是False(即如果len(element)等于0)。这就意味着if element.find('...')并非在测试是否find()方法找到了匹配项;这条语句是在测试匹配到的元素是否包含子元素。想要测试find()方法是否返回了一个元素,则需使用if element.find('...') is not None。

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


感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

相关文章

使用 Python 实现简单的 switch/case 语句的方法

在Python中是没有Switch / Case语句的,很多人认为这种语句不够优雅灵活,在Python中用字典来处理多条件匹配问题字典会更简单高效,对于有一定经验的Python玩家不得不...

Android 兼容性问题:java.lang.UnsupportedOperationException解决办法

Android 兼容性问题:java.lang.UnsupportedOperationException解决办法

在前几天的开发中,遇到这么个非常奇葩的异常,有些手机可以运行,有些手机却直接就崩了,今天就把这异常整理下。 首先还是贴上其异常信息 E/AndroidRuntime: FATAL E...

python获取指定路径下所有指定后缀文件的方法

本文实例讲述了python获取指定路径下所有指定后缀文件的方法。分享给大家供大家参考。具体实现方法如下: # 获取指定路径下所有指定后缀的文件 # dir 指定路径 # ext 指定...

python进阶教程之循环对象

这一讲的主要目的是为了大家在读Python程序的时候对循环对象有一个基本概念。 循环对象的并不是随着Python的诞生就存在的,但它的发展迅速,特别是Python 3x的时代,循环对象正...

SublimeText 2编译python出错的解决方法(The system cannot find the file specified)

[Error 2] The system cannot find the file specified 解决方法:1.环境变量path添加:C:\Python32\Tools\Scrip...