-4

I can make a long string (my_xml) like this:

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)

Is there another cleaner way to do it instead of repeating "my_xml +=" tag?

Kevin
  • 74,910
  • 12
  • 133
  • 166
Drwhite
  • 1,545
  • 4
  • 21
  • 44

2 Answers2

0

If you want to build your page this way, consider using (following the example given in Proper indentation for Python multiline strings )

edited to make the xml line show on the page, and make line breaks work:

elements = Element.objects.all()
my_xml = ('<html type=text/html encoding="utf-8">'
  '&lt;?xml version="1.0" encoding="utf-8"?&gt;<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)
Community
  • 1
  • 1
Floris
  • 45,857
  • 6
  • 70
  • 122
0

You could use a list:

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))
girasquid
  • 15,121
  • 2
  • 48
  • 58