from elementtree import ElementTree as ET import simplejson class Node

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
from elementtree import ElementTree as ET
import simplejson
class Node(object):
"""
Base entity class for storing data tree and wrapping it in XML, JSON etc
"""
def __init__(self, name, attribs=None, nodes=None):
self.name = name
self.attribs = attribs and attribs or {}
self.nodes = nodes and nodes or []
def to_et(self):
"""
Return self content converted to ElemenTree node.
"""
elem = ET.Element(self.name, **self.attribs)
for node in self.nodes:
elem.append(node.to_et())
return elem
def to_xml(self):
"""
Return self content wrapped into XML.
"""
return ET.tostring(self.to_et())
def to_dict(self):
"""
Return self content wrapped into python dicts.
Details about XML --> JSON: http://www.xml.com/pub/a/2006/05/31/converting-between-xml-and-json.html?page=1
"""
elem = {self.name: self.attribs}
for node in self.nodes:
if node.name in elem[self.name]:
elem[self.name][node.name] = [elem[self.name[node.name]]]
elem[self.name][node.name].append(node.to_dict())
else:
elem[self.name].update(node.to_dict())
return elem
def to_json(self):
"""
Return self content wrapped into JSON.
"""
return simplejson.dumps(self.to_dict())