python解析xml配置文件

一、创建xml样例文件,以ascii格式存放

<?xml version="1.0" encoding="utf-8"?>  
<Files>  
    <C2GCarrier fileName="C2G_CARRIER_YYYYMMDD_NNNN.DAT" describe="集团下发的C2G文件" tagClass="Application" tagFormat="Simple" tagId="1">  
    <HeadRecord tagType="Sequence" tagClass="Application" tagFormat="Simple" tagId="33">
        <RecordType tagType="Sequence" tagClass="Application" tagFormat="Simple" tagId="80">记录类型</RecordType> 
        <ProvCode tagType="Sequence" tagClass="Application" tagFormat="Simple" tagId="81">省代码</ProvCode> 
        <FileGenDate tagType="Sequence" tagClass="Application" tagFormat="Simple" tagId="83">文件生成时间</FileGenDate> 
    </HeadRecord> 
    </C2GCarrier>
</Files>


二、python编码遍历节点

#!/usr/bin/python
# -*- coding:utf-8 -*-
'''
Created on 2016年2月24日
'''
from xml.etree import ElementTree
import codecs

def fromFile1(fileName):
    xmlString = open(fileName).read()
    root = ElementTree.fromstring(xmlString)
    return root

def fromFile2(fileName):
    obj = codecs.open(fileName, 'rb', 'gbk')
    xmlString = obj.read().encode('utf-8')
    obj.close()
    root = ElementTree.fromstring(xmlString)
    return root

def loopXml(nodes):
    for node in nodes.iter():
        outstr = node.tag + '=' 
        if node.text != None:
            outstr += node.text
        outstr += '{'
        for attr in node.attrib:
            outstr += attr + ':' + node.attrib[attr] + ','
        outstr += '}'
        print(outstr)
        


if __name__ == '__main__':
    loopXml(fromFile1('E:/work/asn_format.xml'))
    loopXml(fromFile2('E:/work/asn_format.xml'))
    
    pass


三、输出结果

Files=  
    {}
C2GCarrier=  
    {tagId:1,tagClass:Application,tagFormat:Simple,fileName:C2G_CARRIER_YYYYMMDD_NNNN.DAT,describe:集团下发的C2G文件,}
HeadRecord=
        {tagId:33,tagClass:Application,tagType:Sequence,tagFormat:Simple,}
RecordType=记录类型{tagId:80,tagClass:Application,tagType:Sequence,tagFormat:Simple,}
ProvCode=省代码{tagId:81,tagClass:Application,tagType:Sequence,tagFormat:Simple,}
FileGenDate=文件生成时间{tagId:83,tagClass:Application,tagType:Sequence,tagFormat:Simple,}
Files=  
    {}
C2GCarrier=  
    {tagId:1,tagClass:Application,tagFormat:Simple,fileName:C2G_CARRIER_YYYYMMDD_NNNN.DAT,describe:集团下发的C2G文件,}
HeadRecord=
        {tagId:33,tagClass:Application,tagType:Sequence,tagFormat:Simple,}
RecordType=记录类型{tagId:80,tagClass:Application,tagType:Sequence,tagFormat:Simple,}
ProvCode=省代码{tagId:81,tagClass:Application,tagType:Sequence,tagFormat:Simple,}
FileGenDate=文件生成时间{tagId:83,tagClass:Application,tagType:Sequence,tagFormat:Simple,}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

mengyoufengyu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值