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

jens python_gmane at jensdiemer.de
Fre Mar 17 09:11:11 CET 2006


Noch ein update:

===========================================================
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)
         out.write("\t"*deep)

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

     else:
         out.write(repr(data))

     out.write("</%s>\n" % typ)

to_xml(t, out=sys.stdout)

print "-"*79
t = {'foo': {"bar":("jup","jap","schnupp")}}
to_xml(t, out=sys.stdout)
===========================================================

Erzeugt das:
===========================================================
<list>
	<str>'beispiel'</str>
	<int>123</int>
	<str>'noch was'</str>
	<dict>
		<str key="status">'GM'</str>
		<int key="rating">2700</int>
	</dict>
	<dict>
		<str key="status">'Computer'</str>
		<int key="rating">2700</int>
	</dict>
	<dict>
		<str key="status">'Amateur'</str>
		<int key="rating">1400</int>
	</dict>
	<dict>
		<dict key="eins">
			<int key="a">1</int>
			<int key="b">2</int>
		</dict>
		<dict key="zwei">
			<int key="c">2</int>
			<int key="d">3</int>
		</dict>
	</dict>
</list>
-------------------------------------------------------------------------------
<dict>
	<dict key="foo">
		<tuple key="bar">
			<str>'jup'</str>
			<str>'jap'</str>
			<str>'schnupp'</str>
		</tuple>
	</dict>
</dict>
===========================================================


Beim letzten kann man aber sehen, an <tuple key="bar"> das es so einfach 
nicht geht...



-- 
Mfg.

Jens Diemer


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