Code: Alles auswählen
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import sys, time
t = [
"beispiel", 123, 23j, #u'hällø',
{"1": None, "2": True, "3": False},
{'status':'GM', 'rating':2700},
{
"eins": {"a":1, "b":2},
"zwei": {"c":2, "d":3},
},
{'foo': {"bar":("jup","jap","schnupp")}}
]
class XMLPickle:
def __init__(self):
self.encodingMap = {
dict: self.encode_dict,
list: self.encode_iter,
tuple: self.encode_iter,
unicode: self.encode_unicode,
str: str,
int: str,
long: str,
complex: str,
}
def encode_dict(self, data):
result = ""
for k,v in data.iteritems():
result += self.to_xml(v, key=k)
return result
def encode_iter(self, data):
result = ""
for e in iter(data):
result += self.to_xml(e)
return result
def encode_unicode(self, data):
try:
return data.decode('ascii')
except UnicodeError:
return data.encode(
sys.stdout.encoding or sys.getfilesystemencoding()
)
def encodeData(self, data):
# Quick: type()-Mapping
try:
return self.encodingMap[type(data)](data)
except KeyError:
# slow Fallback: isinstance()-Mapping
for encodeType, method in self.encodingMap.iteritems():
if isinstance(data, encodeType):
return method(data)
try:
return encode_iter(e)
except:
return str(data)
def to_xml(self, data, **attributes):
result = ""
typ = data.__class__.__name__
if type(data) in (None,True,False,):
return "<%s></%s>" % (data,data)
if attributes:
startTag = [typ]
for a in attributes.iteritems():
startTag.append('%s="%s"' % a)
startTag = " ".join(startTag)
else:
startTag = typ
return "<%s>%s</%s>" % (
startTag, self.encodeData(data), typ
)
def dumps(self, dataString):
return self.to_xml(dataString)
def durationTest():
start_time = time.time()
xml = XMLPickle()
for i in xrange(10000):
xml.dumps(t)
print "duration: %.2fsec" % (time.time()- start_time)
#~ durationTest()
xml = XMLPickle()
xmlData = xml.dumps(t)
xmlData = "<data>%s</data>" % xmlData
#~ xmlData = xmlData.replace(">",">\n")
#~ xmlData = xmlData.strip()
#~ for e in enumerate(xmlData.split("\n")):
#~ print "%3s - %s" % e
#~ print xmlData
from xml.dom import minidom
# Formatieren und ausgeben
dom = minidom.parseString(xmlData)
print dom.toprettyxml(" ")
Code: Alles auswählen
<?xml version="1.0" ?>
<data>
<list>
<str>
beispiel
</str>
<int>
123
</int>
<complex>
23j
</complex>
<dict>
<NoneType key="1">
None
</NoneType>
<bool key="3">
False
</bool>
<bool key="2">
True
</bool>
</dict>
<dict>
<str key="status">
GM
</str>
<int key="rating">
2700
</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>
<dict>
<dict key="foo">
<tuple key="bar">
<str>
jup
</str>
<str>
jap
</str>
<str>
schnupp
</str>
</tuple>
</dict>
</dict>
</list>
</data>
Außerdem wüßte ich gern, wie man am besten mit unicode umgehen könnte... Aber das kommt wahrscheinlich auf die Art der Verwendung an, was?
Nun müßte ich mir mal überlegen, wie man das wieder zurück wandeln kann... *schau auf BlackJack's Lösung*