Howdy Folks,
The ElementTree library is an excellent way to allow your Python apps to read and manipulate XML files in a Pythonic manner. But what do you do if you want to create XML from a Python object with arbitrary dictionaries and lists?
To tackle this task, I have created the recursive xmlObjectCreator. Its code is noted below. When you pass it an arbitrary Python object and a few other parameters, it will give you back an ElementTree representing the Python object. You can then dump or write the tree to your heart's content.
There is one caveat, however. To avoid unneeded complexity, I did not provide any method by which you can describe metadata. This basically means that for lists, the actual items will have element names set to the list name plus a static string. So, you might have myList['One', 'Two'], and it would generate XML like this:
<myList><myList_item>One</myList_item><myList_item>Two</myList_item></myList>
To run the method, you do this:
xmlObject = xmlObjectCreator
(inputObject, topLevelTag, etreeRootObj, structType, etreeRootObj, True)
The input parameters are as follows:
- inputObject. This your arbitrary Python structure.
- topLevelTag. This is the tag that you want your root level object to have.
- etreeRootObj (parameters 3 and 5). This is a valid ElementTree tree object. It should not have any elements.
- structType: an empty string. This is used internally during recursion.
- True. This is always set to True.
The extra string parameter, root object paremeter and the tailing True are needed because the method is recursive, and it will pass different values for these paremeters depending on the depth of recursion and the current object it's working on. Some folks have suggested alternate, cleaner ways to handle this - and those ways will be implemented in future revisions of the library.
UPDATE: I've updated the code to use introspection instead of try/catch exception blocks.
Keywords: generator, object, python, recursion, recursive, xml


