python jsonToxml

 

 

#!/bin/python
# -*- coding: utf-8 -*-  

from xml.dom.minidom import Document

doc = Document()
root = doc.createElement("sdd")
doc.appendChild(root)

def parse(json,parent):
	for key in json:
		value = json[key]
		if(isinstance(value,str)):
			ele = doc.createElement(key)
			#print value
			ele.appendChild(doc.createTextNode(value))
			parent.appendChild(ele)

		elif(isinstance(value,dict)):
			#print key		
			ele = doc.createElement(key)	
			parent.appendChild(ele)
			parse(value,ele)
		elif(isinstance(value,list)):
			ele = doc.createElement(key)				
			parent.appendChild(ele)			
			
			for i in value:
				parse(i,ele)				

				


ssd = {"provider":"duitang","version":"1.0","piclist":[{"item":{"url":"http://s5.duitang.cn/b7/bao/120525/7lm4z_kqytc2czozbhg6cugfjeg5sckzsew_800x1042.jpg","desc":"content_desc","link":"http%3A%2F%2Fwww.duitang.com%2Fqqphoto%3Ftid%3D14405nw%26goodsid%3D11bpogq","price":"52.00","source":"duitang.com"}},{"item":{"url":"http://s5.duitang.cn/b7/bao/120525/7lm4z_kqytc2czozbhg6cugfjeg5sckzsew_800x1042.jpg","desc":"content_desc","link":"http%3A%2F%2Fwww.duitang.com%2Fqqphoto%3Ftid%3D14405nw%26goodsid%3D11bpogq","price":"52.00","source":"duitang.com"}},{"item":{"url":"http://s5.duitang.cn/b7/bao/120525/7lm4z_kqytc2czozbhg6cugfjeg5sckzsew_800x1042.jpg","desc":"content_desc","link":"http%3A%2F%2Fwww.duitang.com%2Fqqphoto%3Ftid%3D14405nw%26goodsid%3D11bpogq","price":"52.00","source":"duitang.com"}}],"board":{"name":"content_name","desc":"content_desc","category":"1","qq":"121212","create":"0"}}

parse(ssd,root)

print doc.toxml(encoding="UTF-8")

#for s in ssd:
#	print "%s %s"%(isinstance(ssd[s],str),isinstance(ssd[s],dict))

 

 

 

你可能感兴趣的:(python)