Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a dict to XML with attributes

I am using dicttoxml in python for converting dict to XML .

I need to convert the dict to XML attributes.

For example:

dict

[
      {
           "@name":"Ravi",
           "@age":21,
           "college":"Anna University"
       }
]

Output XML

<Student name="Ravi" age=21>
  <college>Anna University</college>
</Student>

code

dicttoxml(dict, custom_root='Student', attr_type=False, root=True)

Actual Output

<Student>
  <key name="name">Ravi</key>
  <key name="age">21</key>
  <college>Anna University</college>
</Student>
like image 935
devanathan Avatar asked Apr 03 '17 12:04

devanathan


2 Answers

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

like image 169
Nishant Srivastava Avatar answered Sep 22 '22 13:09

Nishant Srivastava


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>
like image 26
gatkin Avatar answered Sep 20 '22 13:09

gatkin