我可以像这样制作一个长字符串(my_xml
):
elements = Element.objects.all()
my_xml = '<?xml version="1.0" encoding="utf-8"?>\n'
my_xml += 'description\n'
my_xml += 'document title\n'
my_xml += 'other_infos\n'
for elt in elements:
my_xml += elt.title
my_xml += elt.desc
return HttpResponse(my_xml)
是否有其他更简洁的方法来执行此操作而不是重复“my_xml +=
”标记?
答案 0 :(得分:0)
如果您想以这种方式构建页面,请考虑使用(遵循中给出的示例) Proper indentation for Python multiline strings)
已修改以在页面上显示xml
行,并使换行符有效:
elements = Element.objects.all()
my_xml = ('<html type=text/html encoding="utf-8">'
'<?xml version="1.0" encoding="utf-8"?><br>'
'description<br>'
'document title<br>'
'other_infos<br>')
for elt in elements:
my_xml += elt.title + '<br>'
my_xml += elt.desc + '<br>'
my_xml += '</html>'
return HttpResponse(my_xml)
答案 1 :(得分:0)
您可以使用列表:
elements = Element.objects.all()
xml_parts = ["""
<?xml version="1.0" encoding="utf-8"?>
description
document title
other_infos
"""]
for el in elements:
xml_parts.append(elt.title)
xml_parts.append(elt.desc)
return HttpResponse(''.join(xml_parts))