首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 更多程式設計知識

Python 自訂 XML 解析器:處理非標準節點名稱與 CDATA 區段

     編輯:更多程式設計知識

針對節點名稱以數字開頭、非標準格式的 XML,以正則表達式實作輕量級 XPath 風格解析器。

核心類別


import re

class xmlparse:
    def __init__(self, xmlstr):
        self.xmlstr = xmlstr
        self.xmldom = self.__convet2utf8()
        self.xmlnodelist = []
        self.xpath = ''

    def __get_head(self):
        m = re.match(r'<\?xml.*?\?>', self.xmlstr)
        return m.group() if m else ''

    def __convet2utf8(self):
        head = self.__get_head()
        body = self.xmlstr.replace(head, '')
        if 'gbk' in head:
            return body.decode('gbk').encode('utf-8')
        elif 'gb2312' in head:
            return body.decode('gb2312').encode('utf-8')
        return body

    def parse(self, xpath):
        self.xpath = xpath
        xpatlist = []
        for node in xpath.split('/'):
            if not node: continue
            idx = 0
            if '[' in node:
                node, idx = node.split('[')
                idx = int(idx.rstrip(']'))
            xpatlist.append((f'<{node}>(.*?)', idx))

        xmlstr = self.xmldom
        for pat, idx in xpatlist:
            nodes = re.findall(pat, xmlstr)
            xmlstr = nodes[idx]
            if xmlstr.startswith('

測試範例


xmlstr = 'aaaaa...'
xp = xmlparse(xmlstr)
print(xp.parse('/product_id'))      # aaaaa
print(xp.parse('/product_id[1]'))   # bbbbb
print(xp.parse('/a/product_id'))    # aaaaa

已知限制

  • 同名節點巢狀時正則會誤匹配
  • 不支援屬性查詢
  • 複雜結構建議改用 lxml 或 xml.etree
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved