refactor this dictionary-to-xml converter in python -


This is a small thing, in fact: I have this function that converts hard objects into XML.

Function:

  def dictoxml (d): import from xml.saxutils def def unicodify (o): if o is none: return u '' ; Return Unicode (O) line = [] def addDict (node, offset): for name, value in node.iteritems (): if isinstance (value, dict): lines.append (offset + u "& lt;% s & Gt; "% name" addDict (value, offset + u "4) line .append (offset + u"  "% name") elif isinstance (value, list): item in price For: if isinstance (item, dict): Lines. Offend (offset + u "liebase;% s>"% name ") addDict (object, offset + u" * 4) line .append (offset + u "& lt ; /% S> "% name" Other: lines.append (offset + u "lt;% s>% s & lt; /% s & gt;"% (name, escape (UnicodeFire (item) ), Names) Other: lines.append (offset + u "% s>% s   (name, escape (unicodefe (value) Pre> 

enough for the former, it converts this dictionary

  {'site': {'name': 'stackoverflow', 'blogger': ['jeff' 'Joel']}}  / Pre> 

to:

  site & gt; & lt; Name & gt; Stackoverflow & lt; / Name & gt; & Lt; Blogger & gt; Jeff & lt; / Blogger & gt; & Lt; Blogger & gt; Joel & lt; / Blogger & gt; & Lt; / Site & gt;  

This works, but the addDict function looks a little bit repetitive. I'm sure that it's called addDict , addList < There is a way to re-read in 3 co-recurring works called / code> and addElse , but my mind is stuck. Any help?

In addition, there would be a good way to get rid of the offset + object in each line.

Note : I chose these words because I am trying to match their behavior, which I use in a different part of my project if you On the page are just looking for a dictionary for XML converter, then in some answers there are some really good options (especially).

I saw that you have the similarity in adding items. Using this parallel I have an item I would like to add as function

  def addItem (item, name, offset): ifinstance (item, dict): lines.append (offset + u "& lt;% s & gt;"% name) addDict (item , Offset + u "4) line .append (offset + u" & lt; /% s & gt; "% name) Other: lines.append (offset + u" & lt (value, name, offset) For item: addItem (item, name, offset);% s>% s (name, escape (unicodefe (item)), name add addictive (node, offset) for name: node.iteritems () Value: ifinstance (value, list): addList (value, name, offset) Other: addItem (value, name, offset)  

Consultant Warning: Is no inspection or writing which actually uses the Python.


Comments