[Python-de] Python string,dict,list und Co. <-> XML

jens python_gmane at jensdiemer.de
Fre Mar 17 08:55:33 CET 2006


Stefan Behnel schrieb:
> SyntaxError: invalid syntax


Ich hab es mal weiter verwuschtelt:
_____________________________________________
import sys

t = [
     "beispiel", 123, "noch was",
     {'status':'GM', 'rating':2700},
     {'status':'Computer', 'rating':2700},
     {'status':'Amateur', 'rating':1400},
     {
         "eins": {"a":1, "b":2},
         "zwei": {"c":2, "d":3},
     },
]

def to_xml(data, out, deep=0, **attributes):
     typ = data.__class__.__name__

     attr = [typ]
     for a in attributes.iteritems():
         attr.append('%s="%s"' % a)
     attr = " ".join(attr)

     out.write(
         "%s<%s>" % ("\t"*deep, attr)
     )

     if isinstance(data, dict):
         out.write("\n")
         for k,v in data.iteritems():
             to_xml(v, out, deep+1, key=k)

     elif isinstance(data, list):
         out.write("\n")
         for e in data:
             to_xml(e, out, deep+1)

     else:
         out.write(
             "%s%s" % ("\t"*deep, repr(data))
         )
     out.write(
         "%s%s\n" % ("\t"*deep,"</%s>" % typ)
     )

to_xml(t, out=sys.stdout)
_____________________________________________


Erzeugt allerdings dumme TABs :(


-- 
Mfg.

Jens Diemer


----
CMS in pure Python CGI: http://www.pylucid.org