I need to use Python 2.4.4 to convert XML to and from a Python dictionary. All I need are the node names and values, I'm not worried about attributes because the XML I'm parsing doesn't have any. I can't use ElementTree
because that isn't available for 2.4.4, and I can't use 3rd party libraries due to my work environment. What's the easiest way for me to do this? Are there any good snippets?
Also, if there isn't an easy way to do this, are there any alternative serialization formats that Python 2.4.4 has native support for?
Grey's link includes some solutions that look pretty robust. If you want to roll your own though, you could use xml.dom.node's childNode member recursively, terminating when node.childNode = None.
Question Serialize Python dictionary to XML lists some ways of XML serialization. As for alternative serialization formats, I guess
pickle
module is a nice tool for it.For serializing a Python dict to XML, the following Python class works well for me. Over some other solutions, it has the advantage that it is quite simple and that it does proper XML encoding. The script is based on this answer. It has only one extension: By passing the
list_mappings
dictionary to the constructor, you can specify how a single list item (achild
inside thechildren
attribute in the example below) is named.It gives the following output:
I recently wrote some code to translate XML into a python data structure, although I did have to handle attributes. I used
xml.dom.minidom
rather thanElementTree
, for a similar reason. I haven't actually tested this on Python 2.4.4, but I think it will work. I didn't write a reverse XML generator, though you can probably use the 'lispy_string' function I included to do this.I also included some shortcuts specific to the application I was writing (explained in the docstring), but you might find those shortcuts useful too, from the sounds of it. Essentially, an xml tree technically translates into a dictionary of lists of dictionaries of lists of dictionaries of lists, etc. I omit creating the intermediary lists unless they are necessary, so you can reference elements by
dictname[element1][element2]
rather thandictname[element1][0][element2][0]
and so on.Attribute handling is a little kludgy, I strongly recommend reading the code before doing anything with attributes.
Dicts in python are not ordered, remember this. I have a very basic code, which is small and does not require any external modules. Bad thing is that it does not support any kind of XML attributes, but you said
,so here it is:
Example of usage:
This will print: