In [10]:
sn = lambda nn: "<{}>".format(nn)
en = lambda nn: "</{}>".format(nn)
# pretend we're xml encoding
encodexml = lambda txt: str(txt)
In [2]:
sn('product')
Out[2]:
In [25]:
strct = {'product/id': 0,
'product/shipping/country': 1,
'product/shipping/method': 2,
}
data = [1, 'US', '1-day', 'shirt']
In [31]:
def pathmap_to_tree(dr):
nestedmap = {}
for path, val in dr.items():
paths = path.split('/')
pl = len(paths)
mapnode = nestedmap
for i in range(pl):
current = paths[i]
if (i+1) < pl:
try:
mapnode = mapnode[current]
except KeyError:
mapnode[current] = {}
mapnode = mapnode[current]
else:
mapnode[current] = val
return nestedmap
pathmap_to_tree(strct)
Out[31]:
In [37]:
def tree_to_xml(tr, dt, parent):
string = []
try:
# print (tr)
for node, vals in tr.items():
string.append(sn(node))
string.append(tree_to_xml(vals, dt, node))
string.append(en(node))
except AttributeError:
# print(parent)
return encodexml(data[tr])
return ''.join(string)
tree_to_xml(pathmap_to_tree(strct), data, None)
Out[37]:
In [32]:
strctl = {'product/id': [0],
'product/shipping/country': [1],
'product/shipping/method': [2],
'product/labels/label': [3,4,5]
}
datal = [1, 'US', '1-day', 'shirt', 'clothes', 'nice clothes']
pathmap_to_tree(strctl)
Out[32]:
In [45]:
def tree_to_xml_list(tr, dt, parent):
string = []
try:
# print (tr)
for node, vals in tr.items():
if (isinstance(vals, dict)):
string.append(sn(node))
string.append(tree_to_xml_list(vals, dt, node))
if (isinstance(vals, dict)):
string.append(en(node))
except AttributeError:
child = []
print(tr)
for i in tr:
child.append(sn(parent))
child.append(encodexml(dt[i]))
child.append(en(parent))
ret = ''.join(child)
print(ret)
return ret
return ''.join(string)
tree_to_xml_list(pathmap_to_tree(strctl), datal, None)
# isinstance([], dict)
Out[45]:
In [46]:
strct = {'product/id': 0,
'product/shipping/country': 1,
'product/shipping/method': 2,
}
def pathmap_to_tree(dr):
nestedmap = {}
for path, val in dr.items():
paths = path.split('/')
pl = len(paths)
mapnode = nestedmap
for i in range(pl):
current = paths[i]
if (i+1) < pl:
try:
mapnode = mapnode[current]
except KeyError:
mapnode[current] = {}
mapnode = mapnode[current]
else:
mapnode[current] = val
return nestedmap
pathmap_to_tree(strctl)
Out[46]: