亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

python自定義解析簡單xml格式文件的方法

 更新時間:2015年05月11日 15:51:26   作者:像風(fēng)一樣的自由  
這篇文章主要介紹了python自定義解析簡單xml格式文件的方法,涉及Python解析XML文件的相關(guān)技巧,非常具有實用價值,需要的朋友可以參考下

本文實例講述了python自定義解析簡單xml格式文件的方法。分享給大家供大家參考。具體分析如下:

因為公司內(nèi)部的接口返回的字串支持2種形式:php數(shù)組,xml;結(jié)果php數(shù)組python不能直接用,而xml字符串的格式不是標準的,所以也不能用標準模塊解析?!静粯藴实牡胤绞悄承┕?jié)點會的名稱是以數(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

運行結(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é)點,所以處理起來就比較簡單了。但測試還是發(fā)現(xiàn)有一個bug。即當相同節(jié)點嵌套時會出現(xiàn)正則匹配出問題,該問題的可以通過避免在xpath中出現(xiàn)有嵌套節(jié)點的名稱來解決,否則只有重寫復(fù)雜的機制了。

希望本文所述對大家的Python程序設(shè)計有所幫助。

相關(guān)文章

  • Python類的定義繼承調(diào)用比較方法技巧

    Python類的定義繼承調(diào)用比較方法技巧

    這篇文章主要介紹了Python類的定義繼承調(diào)用比較方法技巧,文章首先通過類的約束展開詳情圍繞主題介紹相關(guān)內(nèi)容,具有一定的參考價值,需要的小伙伴可以參考一下
    2022-06-06
  • python3實現(xiàn)tailf命令的示例代碼

    python3實現(xiàn)tailf命令的示例代碼

    本文主要介紹了python3實現(xiàn)tailf命令的示例代碼,tail -f 是一個linux的操作命令.其主要的是會把文件里的最尾部的內(nèi)容顯顯示在屏幕上,并且不斷刷新,只要文件有變動就可以看到最新的文件內(nèi)容,感興趣的可以了解一下
    2023-11-11
  • python中celery的基本使用詳情

    python中celery的基本使用詳情

    這篇文章主要介紹了python中celery的基本使用詳情,Celery 是由Python 編寫的簡單,靈活,可靠的用來處理大量信息的分布式系統(tǒng),它同時提供操作和維護分布式系統(tǒng)所需的工具。Celery 專注于實時任務(wù)處理,支持任務(wù)調(diào)度
    2022-09-09
  • Python sklearn KFold 生成交叉驗證數(shù)據(jù)集的方法

    Python sklearn KFold 生成交叉驗證數(shù)據(jù)集的方法

    今天小編就為大家分享一篇Python sklearn KFold 生成交叉驗證數(shù)據(jù)集的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-12-12
  • 基于Python實現(xiàn)人臉識別和焦點人物檢測功能

    基于Python實現(xiàn)人臉識別和焦點人物檢測功能

    基于dlib庫的模型,實現(xiàn)人臉識別和焦點人物的檢測。最后呈現(xiàn)的效果為焦點人物的識別框顏色與其他人物框不一樣。對Python人臉識別和焦點人物檢測設(shè)計過程感興趣的朋友一起看看吧
    2021-10-10
  • python將一組數(shù)分成每3個一組的實例

    python將一組數(shù)分成每3個一組的實例

    今天小編就為大家分享一篇python將一組數(shù)分成每3個一組的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-11-11
  • Python隨機生成數(shù)模塊random使用實例

    Python隨機生成數(shù)模塊random使用實例

    這篇文章主要介紹了Python隨機生成數(shù)模塊random使用實例,本文直接給出示例代碼,需要的朋友可以參考下
    2015-04-04
  • python目標檢測YoloV4當中的Mosaic數(shù)據(jù)增強方法

    python目標檢測YoloV4當中的Mosaic數(shù)據(jù)增強方法

    這篇文章主要為大家介紹了python目標檢測YoloV4當中的Mosaic數(shù)據(jù)增強方法,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-05-05
  • python中利用zfill方法自動給數(shù)字前面補0

    python中利用zfill方法自動給數(shù)字前面補0

    python中有一個zfill方法用來給字符串前面補0,非常不錯,下面小編給大家分享了實例代碼,非常不錯,具有參考借鑒價值,需要的朋友參考下吧
    2018-04-04
  • 基于python tornado實現(xiàn)圖床功能

    基于python tornado實現(xiàn)圖床功能

    因為買了阿里/騰訊的云服務(wù)器,但是使用云存儲還需要收費,又加上家里正好有一臺nas,又加上閑的沒事,所以搞了一個小腳本,這個項目主要功能是為typora增加一個自定義圖床,本文給大家介紹基于python tornado實現(xiàn)圖床功能,感興趣的朋友一起看看吧
    2023-08-08

最新評論