python自定義解析簡單xml格式文件的方法
本文實(shí)例講述了python自定義解析簡單xml格式文件的方法。分享給大家供大家參考。具體分析如下:
因?yàn)楣緝?nèi)部的接口返回的字串支持2種形式:php數(shù)組,xml;結(jié)果php數(shù)組python不能直接用,而xml字符串的格式不是標(biāo)準(zhǔn)的,所以也不能用標(biāo)準(zhǔn)模塊解析?!静粯?biāo)準(zhǔn)的地方是某些節(jié)點(diǎn)會的名稱是以數(shù)字開頭的】,所以寫個(gè)簡單的腳步來解析一下文件,用來做接口測試。
#!/usr/bin/env python
#encoding: utf-8
import re
class xmlparse:
def __init__(self, xmlstr):
self.xmlstr = xmlstr
self.xmldom = self.__convet2utf8()
self.xmlnodelist = []
self.xpath = ''
def __convet2utf8(self):
headstr = self.__get_head()
xmldomstr = self.xmlstr.replace(headstr, '')
if 'gbk' in headstr:
xmldomstr = xmldomstr.decode('gbk').encode('utf-8')
elif 'gb2312' in headstr:
xmldomstr = self.xmlstr.decode('gb2312').encode('utf-8')
return xmldomstr
def __get_head(self):
headpat = r'<\?xml.*\?>'
headpatobj = re.compile(headpat)
headregobj = headpatobj.match(self.xmlstr)
if headregobj:
headstr = headregobj.group()
return headstr
else:
return ''
def parse(self, xpath):
self.xpath = xpath
xpatlist = []
xpatharr = self.xpath.split('/')
for xnode in xpatharr:
if xnode:
spcindex = xnode.find('[')
if spcindex > -1:
index = int(xnode[spcindex+1:-1])
xnode = xnode[:spcindex]
else:
index = 0;
temppat = ('<%s>(.*?)</%s>' % (xnode, xnode),index)
xpatlist.append(temppat)
xmlnodestr = self.xmldom
for xpat,index in xpatlist:
xmlnodelist = re.findall(xpat,xmlnodestr)
xmlnodestr = xmlnodelist[index]
if xmlnodestr.startswith(r'<![CDATA['):
xmlnodestr = xmlnodestr.replace(r'<![CDATA[','')[:-3]
self.xmlnodelist = xmlnodelist
return xmlnodestr
if '__main__' == __name__:
xmlstr = '<?xml version="1.0" encoding="utf-8" standalone="yes" ?><resultObject><a><product_id>aaaaa</product_id><product_name><![CDATA[bbbbb]]></a><b><product_id>bbbbb</product_id><product_name><![CDATA[bbbbb]]></b></product_name></resultObject>'
xpath1 = '/product_id'
xpath2 = '/product_id[1]'
xpath3 = '/a/product_id'
xp = xmlparse(xmlstr)
print 'xmlstr:',xp.xmlstr
print 'xmldom:',xp.xmldom
print '------------------------------'
getstr = xp.parse(xpath1)
print 'xpath:',xp.xpath
print 'get list:',xp.xmlnodelist
print 'get string:', getstr
print '------------------------------'
getstr = xp.parse(xpath2)
print 'xpath:',xp.xpath
print 'get list:',xp.xmlnodelist
print 'get string:', getstr
print '------------------------------'
getstr = xp.parse(xpath3)
print 'xpath:',xp.xpath
print 'get list:',xp.xmlnodelist
print 'get string:', getstr
運(yùn)行結(jié)果:
xmlstr: <?xml version="1.0" encoding="utf-8" standalone="yes" ?><resultObject><a><product_id>aaaaa</product_id><product_name><![CDATA[bbbbb]]></a><b><product_id>bbbbb</product_id><product_name><![CDATA[bbbbb]]></b></product_name></resultObject> xmldom: <resultObject><a><product_id>aaaaa</product_id><product_name><![CDATA[bbbbb]]></a><b><product_id>bbbbb</product_id><product_name><![CDATA[bbbbb]]></b></product_name></resultObject> ------------------------------ xpath: /product_id get list: ['aaaaa', 'bbbbb'] get string: aaaaa ------------------------------ xpath: /product_id[1] get list: ['aaaaa', 'bbbbb'] get string: bbbbb ------------------------------ xpath: /a/product_id get list: ['aaaaa'] get string: aaaaa
因?yàn)榉祷氐膞ml格式比較簡單,沒有帶屬性的節(jié)點(diǎn),所以處理起來就比較簡單了。但測試還是發(fā)現(xiàn)有一個(gè)bug。即當(dāng)相同節(jié)點(diǎn)嵌套時(shí)會出現(xiàn)正則匹配出問題,該問題的可以通過避免在xpath中出現(xiàn)有嵌套節(jié)點(diǎn)的名稱來解決,否則只有重寫復(fù)雜的機(jī)制了。
希望本文所述對大家的Python程序設(shè)計(jì)有所幫助。
相關(guān)文章
python3實(shí)現(xiàn)tailf命令的示例代碼
本文主要介紹了python3實(shí)現(xiàn)tailf命令的示例代碼,tail -f 是一個(gè)linux的操作命令.其主要的是會把文件里的最尾部的內(nèi)容顯顯示在屏幕上,并且不斷刷新,只要文件有變動就可以看到最新的文件內(nèi)容,感興趣的可以了解一下2023-11-11
Python sklearn KFold 生成交叉驗(yàn)證數(shù)據(jù)集的方法
今天小編就為大家分享一篇Python sklearn KFold 生成交叉驗(yàn)證數(shù)據(jù)集的方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-12-12
基于Python實(shí)現(xiàn)人臉識別和焦點(diǎn)人物檢測功能
基于dlib庫的模型,實(shí)現(xiàn)人臉識別和焦點(diǎn)人物的檢測。最后呈現(xiàn)的效果為焦點(diǎn)人物的識別框顏色與其他人物框不一樣。對Python人臉識別和焦點(diǎn)人物檢測設(shè)計(jì)過程感興趣的朋友一起看看吧2021-10-10
python將一組數(shù)分成每3個(gè)一組的實(shí)例
今天小編就為大家分享一篇python將一組數(shù)分成每3個(gè)一組的實(shí)例,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-11-11
Python隨機(jī)生成數(shù)模塊random使用實(shí)例
這篇文章主要介紹了Python隨機(jī)生成數(shù)模塊random使用實(shí)例,本文直接給出示例代碼,需要的朋友可以參考下2015-04-04
python目標(biāo)檢測YoloV4當(dāng)中的Mosaic數(shù)據(jù)增強(qiáng)方法
這篇文章主要為大家介紹了python目標(biāo)檢測YoloV4當(dāng)中的Mosaic數(shù)據(jù)增強(qiáng)方法,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05
python中利用zfill方法自動給數(shù)字前面補(bǔ)0
python中有一個(gè)zfill方法用來給字符串前面補(bǔ)0,非常不錯,下面小編給大家分享了實(shí)例代碼,非常不錯,具有參考借鑒價(jià)值,需要的朋友參考下吧2018-04-04
基于python tornado實(shí)現(xiàn)圖床功能
因?yàn)橘I了阿里/騰訊的云服務(wù)器,但是使用云存儲還需要收費(fèi),又加上家里正好有一臺nas,又加上閑的沒事,所以搞了一個(gè)小腳本,這個(gè)項(xiàng)目主要功能是為typora增加一個(gè)自定義圖床,本文給大家介紹基于python tornado實(shí)現(xiàn)圖床功能,感興趣的朋友一起看看吧2023-08-08

