Python解析XML文件

今天学习如何利用Python来解析XML文档。

 

给定一个XML文件,现在我们用Python来提取里面的内容。


    
        
             11111111
             120
             15.0
        
    


 

Python代码:

import xml.etree.ElementTree as ET

class MeiTuanParser:
    def __init__(self):
        self.meituan_deal_set = []

    def parse(self,filepath):
        tree = ET.parse(filepath)
        root = tree.getroot()
        for data in root.iter('data'):
            deal = data.find('deal')

            meituan_deal = {}
            if deal is not None:
                try:
                    meituan_deal['deal_id'] = deal.find('deal_id').text
                except Exception, exp:
                    print "No deal id"
                try:
                    meituan_deal['sales'] = int(deal.find('sales_num').text)
                except Exception, exp:
                    print "Invalid sales number"
                try:
                    meituan_deal['price'] = float(deal.find('price').text)
                except Exception, exp:
                    print "Invalid price"

                self.meituan_deal_set.append(meituan_deal)

        return self.meituan_deal_set

if __name__ == '__main__':
    parser = MeiTuanParser()
    deals = parser.parse('meituan.xml')
    print deals
        


 

 

 

 

 

你可能感兴趣的:(Python)