您的位置:首页 > 编程语言 > Python开发

python解析xml配置文件

2017-06-04 00:00 423 查看
一、创建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,}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: