[Django]-Translate xml string to Python list

0👍

You can use this code sample:

from xml.etree import cElementTree as ET
xml = ET.fromstring(xmlData)

for child in xml.iter('field'):
    print child.tag, child.attrib, child.text

to iterate over all XML elements named field and print to the console their tag, attributes and text value.

Check out xml.etree documentation for more samples.

Django view

In order to render parsed XML data as a view in Django application you need view and template.

Assuming you have a Django application called app installed in your project.

app/views.py

from xml.etree import cElementTree as ET

from django.http import HttpResponse
from django.shortcuts import render
from django.template import Context, loader


def xml_view(request):
    xmlData = """<?xml version="1.0" encoding="utf-8"?> 
    <django-objects version="1.0">
    <object model="task.task" pk="4">
    <field name="name" type="CharField">foo</field>
    <field name="mission_id" type="IntegerField">1</field>
    <field name="parent_task_id" type="IntegerField">20</field>
    </object>
    <object model="task.task" pk="7">
    <field name="name" type="CharField">bar</field>
    <field name="mission_id" type="IntegerField">2</field>
    <field name="parent_task_id" type="IntegerField">10</field>
    </object></django-objects>"""

    xml = ET.fromstring(xmlData)

    fields = []
    for obj in xml.iter("object"):
        fields.append({'name': obj.find("field[@name='name']").text,
                       'mission_id': obj.find("field[@name='mission_id']").text,
                       'parent_task_id': obj.find("field[@name='parent_task_id']").text,
                       })

    t = loader.get_template('your_app/xml_view.html')
    c = Context({'elem_list': fields})
    return HttpResponse(t.render(c))

app/templates/app/xml_view.html

<html lang="en">
  <body>
    <table>
      <tr>
        <th>Name</th>
        <th>Mission ID</th>
        <th>Parent Task ID</th>
      </tr>
      {% for elem in elem_list %}
      <tr>
        <td>{{ elem.name }}</td>
        <td>{{ elem.mission_id }}</td>
        <td>{{ elem.parent_task_id }}</td>
      </tr>
      {% endfor %}
  </body>
</html>

Leave a comment