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>
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 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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With