我需要将从下面函数中得到的xml写入一个文件。有人能帮我完成这个代码:
import json
import urllib
results = json.load(urllib.urlopen("http://www.kimonolabs.com/api/4v1t8lgk?apikey=880a9bdbfb8444e00e2505e1533970a7"))
def json2xml(json_obj, line_padding=""):
result_list = list()
json_obj_type = type(json_obj)
if json_obj_type is list:
for sub_elem in json_obj:
result_list.append(json2xml(sub_elem, line_padding))
f= open('tori_json.xml', 'w')
f.write(str(json_obj))
f.close()
return "\n".join(result_list)
if json_obj_type is dict:
for tag_name in json_obj:
sub_obj = json_obj[tag_name]
result_list.append("%s<%s>" % (line_padding, tag_name))
result_list.append(json2xml(sub_obj, "\t" + line_padding))
result_list.append("%s</%s>" % (line_padding, tag_name))
return "\n".join(result_list)
return "%s%s" % (line_padding, json_obj)
因此,当我运行函数json2xml(results)时,它会将xml写入文件。在
可能最好使用一些xml processing lib
此代码使用BeautifulSoup。JSON结构需要一些额外的信息才能成为一个像样的XML,所以我添加了一些“product”标记来封装每个产品。
相关问题 更多 >
编程相关推荐