views:

399

answers:

2

Hello guys, I've a program that reads a xml document from a socket, so I've the xml document stored in a string which I would like to convert directly to a python dictionary, the same way it is done in django's simplejson library.

Take as an example:

str ="<?xml version="1.0" ?><person><name>john</name><age>20</age></person"
dic_xml = convert_to_dic(str)

Then dic_xml would look like {'person' : { 'name' : 'john', 'age' : 20 } }

Thanks in advance, Ze Maria

A: 

The easiest to use XML parser for Python is ElementTree (as of 2.5x and above it is in the standard library xml.etree.ElementTree). I don't think there is anything that does exactly what you want out of the box. It would be pretty trivial to write something to do what you want using ElementTree, but why convert to a dictionary, and why not just use ElementTree directly.

fuzzy lollipop
+2  A: 

Check out this link, it may be what you're looking for.

It was the first result in Google when searching "python xml to dict".

And here's a link to an ActiveState solution.

tgray