python xml解析實(shí)例詳解
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è)能代表整篇文檔的對象。這不是根元素。要獲得根元素的引用可以調(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查找失?。?br />
使用find要注意在布爾上下文中,如果ElementTree元素對象不包含子元素,其值則會(huì)被認(rèn)為是False(即如果len(element)等于0)。這就意味著if element.find('...')并非在測試是否find()方法找到了匹配項(xiàng);這條語句是在測試匹配到的元素是否包含子元素。想要測試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
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
- Python使用lxml模塊和Requests模塊抓取HTML頁面的教程
- 在windows系統(tǒng)中實(shí)現(xiàn)python3安裝lxml
- 深入解讀Python解析XML的幾種方式
- Python實(shí)現(xiàn)將xml導(dǎo)入至excel
- 詳細(xì)解讀Python中解析XML數(shù)據(jù)的方法
- Python使用minidom讀寫xml的方法
- Python lxml模塊安裝教程
- Python中使用ElementTree解析XML示例
- python基于xmlrpc實(shí)現(xiàn)二進(jìn)制文件傳輸?shù)姆椒?/a>
- python解析xml文件實(shí)例分析
相關(guān)文章
python函數(shù)存儲(chǔ)在模塊的優(yōu)點(diǎn)及用法總結(jié)
在本篇文章里小編給大家整理了一篇關(guān)于python函數(shù)存儲(chǔ)在模塊的優(yōu)點(diǎn)及用法相關(guān)內(nèi)容,有興趣的朋友們可以跟著學(xué)習(xí)下。2021-10-10Gradio機(jī)器學(xué)習(xí)模型快速部署工具quickstart前篇
這篇文章主要為大家介紹了Gradio機(jī)器學(xué)習(xí)模型快速部署工具quickstart準(zhǔn)備原文翻譯,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04python開發(fā)準(zhǔn)備工作之配置虛擬環(huán)境(非常重要)
這篇文章主要介紹了python開發(fā)準(zhǔn)備工作之配置虛擬環(huán)境(非常重要),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2019-02-02Pytorch實(shí)現(xiàn)Fashion-mnist分類任務(wù)全過程
這篇文章主要介紹了Pytorch實(shí)現(xiàn)Fashion-mnist分類任務(wù)全過程,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-12-12