abstract:這篇文章主要介紹了python xml解析實例詳解的相關資料python xml解析first.xml <info> <person > <id>1</id> <name>fsy</name> <age >24</age> </person> <
這篇文章主要介紹了python xml解析實例詳解的相關資料
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()函數(shù)會返回一個能代表整篇文檔的對象。這不是根元素。要獲得根元素的引用可以調(diào)用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只查詢直接的子節(jié)點 >>> 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查找失?。?br/>
使用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 xml解析實例詳解請關注PHP中文網(wǎng)(ipnx.cn)其他文章!