简体   繁体   English

使用python将xml数据写入文件

[英]writing xml data to file using python

I need to write the xml i get from the function below to a file. 我需要将我从下面的函数获取的xml写入文件。 Can someone help me finish this code: 有人可以帮我完成以下代码:

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)

So when i run the function json2xml(results) it would write the xml to file. 因此,当我运行函数json2xml(results)时,它将xml写入文件。

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

probably better using some xml processing lib 使用一些xml处理库可能更好

This code uses BeautifulSoup . 此代码使用BeautifulSoup The JSON structure needs a little extra information for it to be a decent XML, so I added some 'product' tags to encapsulate each product. 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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM