python 转化xml为json的一个小例子
来源:互联网 发布:爸爸网络用语怎么叫 编辑:程序博客网 时间:2024/06/05 19:20
Python将xml转化为json文件的一个小例子(apns-conf.xml是安卓系统中apn的配置文件):
#!/usr/bin/pythonimport jsonimport base64import osfrom xml.etree import ElementTree#----------------------------------------------------# Global Variables#----------------------------------------------------srcRootPath = ''TargetISP = os.environ.get('TARGET_ISP') #os.environ.get()获取系统变量 if not TargetISP: TargetISP = ''APNFileSrc = 'apns-conf.xml' #apns-conf.xml文件所在路径APNTargetPath = 'apn.json' #转化生成的apn.json文件的路径textString = '{\n'def printOtherValues(elem): # <apn carrier="Orange World" # mcc="208" mnc="01" # apn="orange" # user="orange" # password="orange" # server="http://www.orange.fr" # proxy="" port="" mmsc="" mmsproxy="" mmsport="" type="default,supl" authtype="1" spn="Orange F" mvno_type="spn" mvno_match_data="Orange F" protocol="IP" roaming_protocol="IP" /> global textString apnVars = ["carrier","apn","user","password","server","proxy","port","mmsc","mmsproxy","mmsport","type","authtype",'spn',"mvno_type","mvno_match_data","protocol","roaming_protocol"] #使用数组apnVars来保存apn节点中的其它元素,有利于根据节点内容的电话增加或者删除元素 apnText = '\n {' typeString = '[' attributes = elem.attrib for i in range(0,len(apnVars)) : #循环遍历apn节点中的其它元素 if (apnVars[i] != 'type' and attributes.get(apnVars[i])) : apnText += ('"'+ apnVars[i] + '"'+':' + '"%s",'%(elem.attrib[apnVars[i]])) elif (apnVars[i] == 'type' and attributes.get(apnVars[i])) : typeText = elem.attrib[apnVars[i]].split(",") for item in typeText: typeString += ('"' + item + '"' + ',') typeString = (typeString[:-1] + ']') apnText += ('"type"'+':%s,'%(typeString)) apnText = apnText[:-1] apnText += '},' textString += apnTextdef getMNCValues(mccValue,*elems): global textString mncValues = [] for elem in elems: if (elem.attrib['mcc'] == mccValue): mncValues.append(elem.attrib['mnc']) #获取相同mnc值节点的mnc值,并保存在mncValues数组中 mncList = sorted(set(mncValues)) for mncValue in mncList: textString += ' "'+mncValue+'": [' for elem in elems: if (elem.attrib['mcc'] == mccValue): if (elem.attrib['mnc'] == mncValue): #获取相同mcc、mnc值节点中的其它元素 printOtherValues(elem) textString = textString[:-1] if (mncValue == mncList[-1]): textString += '\n ]\n' else : textString += '\n ],\n'def xml2json(APNFileSrc): global textString mccValues = [] """Convert an ElementTree or Element into a JSON string.""" fIn = open(APNFileSrc, 'r') text = fIn.read() fIn.close() elems = ElementTree.fromstring(text) #使用ElementTree解析xml文件 for elem in elems: #获取节点中所有的mcc值,并保存在mccValues数组中 mccValues.append(elem.attrib['mcc']) mccList = sorted(set(mccValues)) #使用set去除数组中的重复元素,然后排序 for mccValue in mccList: textString += '"'+mccValue+'": {\n' getMNCValues(mccValue, *elems) #获取mcc值相同时的mnc值 textString += '},\n' textString = textString[:-2] textString += '\n}' return textStringdef main(): if not os.path.exists(APNFileSrc): #当apns-conf.xml文件不存在时 print '------------------------------------' print 'no apns_conf.xml.' return out = xml2json(APNFileSrc) #xml2json函数解析apns-conf.xml文件 fOut = open(APNTargetPath, 'wb') fOut.write(out.encode("utf-8")) fOut.close()if __name__ == "__main__": main() #python脚本的入口函数apns-conf.xml文件转化成的json文件类似如下:apns-conf.xml:<apn carrier="Orange World" mcc="208" mnc="01" apn="orange" user="orange” /> <apn carrier="Orange World" mcc="208" mnc="01" apn="apple" user="apple"/> <apn carrier="Orange World" mcc="208" mnc="03" apn="hello" user="hello"/> <apn carrier="Orange World" mcc="211" mnc="03" apn="world" user="world"/>apn.json :{"208":{ "01":{ {"apn":"orange", "user":"orange"}, {"apn":"apple", "user":"apple"} }, "03":{ {"apn":"hello", "user":"hello"} }},"211":{ "03":{ {"apn":"world", "user":"world"} }}
阅读全文
0 0
- python 转化xml为json的一个小例子
- java JSON转化为对象的例子
- java把字符串转化为二进制,再把二进制转换成字符串的一个小例子
- python的一个小例子
- 一个json转xml的例子
- json+jsp+JQuery 的一个小例子
- 一个json拼接的小例子
- 将XML文件转化为JSON格式的文件
- 【python】复杂对象的创建过程与转化为json
- 初学python的一个小例子
- 一个整理桌面的python小例子
- python抓取网页的一个小例子
- python爬虫的一个小例子
- json的小例子
- python里json的一个小bug
- 将GBK汉字转化为拼音的Python小程序
- [XML]RSS一个小例子
- NSString 转化为 NSUrl 的一个小问题
- 关于锚点如何不用a标签也能实现跳转
- Android布局
- Drools7在Intellij IDEA下的引入静态方法错误提示
- 关于Java中使用split()方法时报ArrayIndexOutOfBoundsException数组越界异常解决方法
- 用cookie实现自动登录
- python 转化xml为json的一个小例子
- 开源地图mapbox自定义
- Kafka Producer编程一
- 使用Glide对网络图片进行圆形和圆角的处理
- zcmu 1893: String Game
- Problem 2 Even Fibonacci numbers
- 当日历遇上奇葩需求
- MT和MD的区别
- table 表格细线条实现方式