代码示例:通过Python直接解析xml并转换为json,保存json语句文件再加载解析json

Python脚本内容

# -*- coding: cp936 -*-
import json

print "aaa"

d = {"a": 1, "c": 3, "b": 2}

with open("test.json1", "w") as f:
    json.dump(d, f)

with open("test.json1", "r") as f:
    d1 = json.load(f)

print d1
print d1['a']
print d1["c"]
print d1["b"]

print d1.keys


from xml.etree import ElementTree as et;  
import json  
  
#从xml文件读取结点 转换为json格式,并保存到文件中  
print('read node from xmlfile, transfer them to json, and save into jsonFile:')  
root=et.parse("testXml.xml");
print "ddddd"
f=open('test.json','a',encoding="utf8");  
for each in root.getiterator("person"):  
    tempDict=each.attrib  
    for childNode in each.getchildren():  
        tempDict[childNode.tag]=childNode.text  
    tempJson=json.dumps(tempDict,ensure_ascii=False)  
    print(tempJson)  
    f.write(tempJson+"\n");  
f.close()  
  
  
   
    zs  
    male的  
   
   
    ls  
    female  
  
   
    ls  
    female  
   

#从json文件中读取,并打印 print('read json from jsonfile:') for eachJson in open('testJson.json','r',encoding='utf8'): tempStr=json.loads(eachJson); print(tempStr)
 
  

xml内容(命名为testXml.xml)

  
  
   
    zs  
    male的  
   
   
    ls  
    female  
  
   
    ls  
    female  
   



你可能感兴趣的:(代码示例:通过Python直接解析xml并转换为json,保存json语句文件再加载解析json)