abstract:這篇文章主要介紹了python xml解析實(shí)例詳解的相關(guān)資料python xml解析first.xml <info> <person > <id>1</id> <name>fsy</name> <age >24</age> </person> <
這篇文章主要介紹了python xml解析實(shí)例詳解的相關(guān)資料
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ù)會(huì)返回一個(gè)能代表整篇文檔的對(duì)象。這不是根元素。要獲得根元素的引用可以調(diào)用getroot()方法。 tree = etree.parse(file) root = tree.getroot() return root
得到信息
def print_node(node): '''''打印結(jié)點(diǎn)基本信息''' 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é)點(diǎn) >>> 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()方法用來返回第一個(gè)匹配到的元素。當(dāng)我們認(rèn)為只會(huì)有一個(gè)匹配,或者有多個(gè)匹配但我們只關(guān)心第一個(gè)的時(shí)候,這個(gè)方法是很有用的。 >>> 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元素對(duì)象不包含子元素,其值則會(huì)被認(rèn)為是False(即如果len(element)等于0)。這就意味著if element.find('...')并非在測(cè)試是否find()方法找到了匹配項(xiàng);這條語(yǔ)句是在測(cè)試匹配到的元素是否包含子元素。想要測(cè)試find()方法是否返回了一個(gè)元素,則需使用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
更多關(guān)于python xml解析實(shí)例詳解請(qǐng)關(guān)注PHP中文網(wǎng)(m.miracleart.cn)其他文章!