python自定義解析簡單xml格式文件的方法
本文實例講述了python自定義解析簡單xml格式文件的方法。分享給大家供大家參考。具體分析如下:
因為公司內(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ù)字開頭的】,所以寫個簡單的腳步來解析一下文件,用來做接口測試。
#!/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
因為返回的xml格式比較簡單,沒有帶屬性的節(jié)點(diǎn),所以處理起來就比較簡單了。但測試還是發(fā)現(xiàn)有一個bug。即當(dāng)相同節(jié)點(diǎn)嵌套時會出現(xiàn)正則匹配出問題,該問題的可以通過避免在xpath中出現(xiàn)有嵌套節(jié)點(diǎn)的名稱來解決,否則只有重寫復(fù)雜的機(jī)制了。
希望本文所述對大家的Python程序設(shè)計有所幫助。
相關(guān)文章
淺談keras中的后端backend及其相關(guān)函數(shù)(K.prod,K.cast)
這篇文章主要介紹了淺談keras中的后端backend及其相關(guān)函數(shù)(K.prod,K.cast),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06
python實現(xiàn)apahce網(wǎng)站日志分析示例
這篇文章主要介紹了python實現(xiàn)apahce網(wǎng)站日志分析示例,需要的朋友可以參考下2014-04-04
pytorch 求網(wǎng)絡(luò)模型參數(shù)實例
今天小編就為大家分享一篇pytorch 求網(wǎng)絡(luò)模型參數(shù)實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-12-12
python數(shù)據(jù)可視化之初探?Seaborn
Seaborn?是一個基于?Matplotlib?的?Python?數(shù)據(jù)可視化庫,它提供了更高級別的接口,使得創(chuàng)建美觀的統(tǒng)計圖形變得非常簡單,在這篇文章中,我們將討論?Seaborn?的基礎(chǔ)使用方法,包括如何創(chuàng)建各種常見的統(tǒng)計圖形2023-07-07
python seaborn heatmap可視化相關(guān)性矩陣實例
這篇文章主要介紹了python seaborn heatmap可視化相關(guān)性矩陣實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06

