Converting a dict to XML with attributes

I might suggest declxml (full disclosure: I wrote it). With declxml, you create an object called a processor which declaratively defines the structure of your XML. You can use the processor to both parse and serialize XML data. declxml works with serializing to and from dictionaries, objects, and namedtuples. It handles attributes and arrays of elements and performs basic validation.

import declxml as xml


student = {
    'name':'Ravi',
    'age':21,
    'college':'Anna University'
}

student_processor = xml.dictionary('Student', [
    xml.string('.', attribute='name'),
    xml.integer('.', attribute='age'),
    xml.string('college')
])

xml.serialize_to_string(student_processor, student, indent='    ')

Which produces the desired output

<?xml version="1.0" ?>
<Student age="21" name="Ravi">
    <college>Anna University</college>
</Student>

This is not supported by dicttoxml as of yet, though the issue has been open from a long time. https://github.com/quandyfactory/dicttoxml/issues/27

Though if your needs are not that complex, you can try this simple serializer out.

https://gist.github.com/reimund/5435343/

found it here :- Serialize Python dictionary to XML


I had a similar requirement to convert XML to dict and vice versa. I used a library called xmltodict. This lib allows you to reverse from dict to xml with attributes.

dict

xmldata = { 'student': {
       "@name":"Ravi",
       "@age":21,
       "college":"Anna University"
}}

code

import xmltodict

print(xmltodict.unparse(xmldata, pretty=True))