使用python将xml数据写入文件

时间:2014-05-02 09:44:23

标签: python xml json

我需要将从下面的函数中获取的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写入文件。

2 个答案:

答案 0 :(得分:1)

with open("data.xml",'w') as f:
    for line in json2xml(results):
        f.write(line.encode('utf-8'))

可能更好地使用一些xml processing lib

答案 1 :(得分:0)

此代码使用BeautifulSoup。 JSON结构需要一些额外的信息才能成为一个不错的XML,因此我添加了一些“产品”标签来封装每个产品。

from copy import deepcopy
import json
import re
import urllib

from BeautifulSoup import BeautifulStoneSoup, Tag, NavigableString

results = json.load(urllib.urlopen("http://www.kimonolabs.com/api/4v1t8lgk?apikey=880a9bdbfb8444e00e2505e1533970a7"))

class named_list(list):
    def __init__(self, name, *args, **kwargs):
        self.name = name
        super(named_list, self).__init__(*args, **kwargs)

    def __repr__(self):
        return "<named_list %s: %s>" % (self.name, super(named_list, self).__repr__())

def dict_recurse(obj, obj_parent, nameless_default = "product"):
    olist = []
    if isinstance(obj, list):
        for x in obj:
            olist.extend(dict_recurse(x, obj))
    elif isinstance(obj, dict):
        for x in sorted(obj.keys()):
            olist.append(named_list(x, dict_recurse(obj[x], obj)))
        if isinstance(obj_parent, list):
            olist = [named_list(nameless_default, olist)]
    else:
        olist.append(obj)
    return olist

def tag_tree_build(ilist, top_tag, soup):
    if isinstance(ilist, named_list):
        cur_tag = Tag(soup, ilist.name)
        for q in ilist:
            tag_tree_build(q, cur_tag, soup)
        top_tag.insert(len(top_tag), cur_tag)
    elif isinstance(ilist, list):
        for q in ilist:
            tag_tree_build(q, top_tag, soup)
    else:
        cur_str = NavigableString(re.sub("\s+", " ", unicode(ilist)))
        top_tag.insert(len(top_tag), cur_str)

nested = dict_recurse(results, results)
soup = BeautifulStoneSoup()
tag_tree_build(nested, soup, soup)
file("finnish.xml", "w").write(soup.prettify())
file("finnish.json", "w").write(json.dumps(results, sort_keys = True, indent = 4))