简体   繁体   English

服务动态生成的xml文件,以使用字符编码信息在Django中下载

[英]Serve dynamically generated xml file to download in Django with character encoding information

I need to generate a XML file dynamically in Django to download. 我需要在Django动态生成XML文件才能下载。

I can do this with the code below, but without the character encoding information: 我可以使用下面的代码来执行此操作,但是没有字符编码信息:

import xml.etree.ElementTree as ET


def get_xml():
    my_xml = ET.Element('foo', attrib={'bar': 'bla'})
    my_str = ET.tostring(my_xml, 'utf-8', short_empty_elements=False)
    return my_str.decode('utf-8')

# my view
def download_xml_file(request):
    response = HttpResponse(get_xml(), content_type="application/xml")
    response['Content-Disposition'] = 'inline; filename=myfile.xml'
    return response

I can add the character encoding information with the code below, but writing in a file in the server first: 我可以使用以下代码添加字符编码信息,但是首先要在服务器中写入文件:

def get_xml():
    my_xml = ET.Element('foo', attrib={'bar': 'bla'})
    tree = ET.ElementTree(my_xml)
    fname = 'myfile.xml'
    tree.write(fname, xml_declaration=True, encoding='utf-8')
    with open(fname, 'r') as fh:
        my_str = fh.read()
    return my_str

How do I serve the xml file to download with character encoding information without writing in the server first? 我如何在不先写入服务器的情况下提供带有字符编码信息的xml文件下载?

I found two ways to solve the question: 我发现了两种解决问题的方法:

1) Concatenate the character encoding information as string (duh!): 1)将字符编码信息连接为字符串(duh!):

def get_xml():
    my_xml = ET.Element('foo', attrib={'bar': 'bla'})
    my_str = ET.tostring(my_xml, 'utf-8', short_empty_elements=False)
    enc = '<?xml version="1.0" encoding="utf-8"?>'
    return enc += my_str.decode('utf-8')

2) Use xml.dom.minidom.parseString and xml.dom.minidom.Node.toxml : 2)使用xml.dom.minidom.parseStringxml.dom.minidom.Node.toxml

def get_xml():
    my_xml = ET.Element('foo', attrib={'bar': 'bla'})
    my_str = ET.tostring(my_xml, 'utf-8', short_empty_elements=False)
    return xml.dom.minidom.parseString(my_str).toxml(encoding='utf-8')

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

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