python读取xml配置_python解析xml配置文件

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

记录类型

省代码

文件生成时间

二、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,}

你可能感兴趣的:(python读取xml配置)