0

I'm trying to send an XML file as a payload over HTTP to a Django development server on my local machine. I have no issues sending HTTP POST requests with JSON payloads and I understand that XML functionality does not come with Django REST framework out of the box, so I installed djangorestframework-xml. I used a parser decorator in my api view function definition like so:

@api_view(['GET', 'POST'])
@parser_classes([XMLParser])
def my_view(request):
    if request.method =='GET':
        pass
    
    if request.method == 'POST':
        return Response({'received_data': request.data})

The issue is, the way the data is structured, the information I need to parse is stored as tag attributes, like so:

<CEF>
    <Element>
        <p x="1" y="2"/>
    </Element>
</CEF>

And when it is received by Django, request.data does not include attribute tag data:

{
    "received_data": {
        "Element": {
            "p": null
        }
    }
}

Is there a header I could add to the HTTP request to preserve the xml tag attribute data? Any pointers are greatly appreciated!

I tried different configurations for the tag data, but ultimately, I have no control over the data source and the way the data is structured in the xml file.

  • It is possible xml.etree.ElementTree to parse in Python but you needs to decide how to convert attribute of XML to JSON. https://stackoverflow.com/questions/4056419/how-would-i-express-xml-tag-attributes-in-json – Bench Vue Jan 02 '23 at 03:38

1 Answers1

0

I was able to find a solution for this, so a short description here in case someone ever needs it.

What worked for me was using the DRF built-in FileUploadParser rather than the XMLParser for my_view function. As per documentation, I included the appropriate header to the request: Content-Disposition: attachment; filename=upload.xml.

This allowed DRF to receive the entire XML file in the request, tags attributes included. The file can then be parsed via xml.etree.ElementTree, as was suggested by the first comment to the question.