-
-
Notifications
You must be signed in to change notification settings - Fork 310
/
xmler.py
135 lines (108 loc) · 4.13 KB
/
xmler.py
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
"""
Converts a Python dictionary to a valid XML string
https://github.com/watzon/xmler Slightly modified and adapted for py3.
TODO: project seems dead but it's very small and shall be easy to maintain.
Decide if we want to keep it here or contribute back.
"""
from xml.dom import minidom
from xml.etree.ElementTree import Element, tostring
__version__ = "0.2.0"
version = __version__
def dict2xml(input_dict, encoding="utf-8", pretty=False):
"""Converts a python dictionary into a valid XML string
Args:
- encoding specifies the encoding to be included in the encoding
segment. If set to False no encoding segment will be displayed.
- customRoot defines the tag to wrap the returned output. Can be
a string, dictionary, or False if no custom root is to be used.
Returns:
A XML formatted string representing the dictionary.
Examples:
```
dic = {
"Envelope": {
"@ns": "soapenv",
"@attrs": {
"xmlns:soapenv": "http://schemas.xmlsoap.org/soap/envelope/",
"xmlns:urn": "urn:partner.soap.sforce.com"
},
"Header": {
"@ns": "soapenv",
"SessionHeader": {
"@ns": "urn",
"sessionId": {
"@ns": "urn",
"@value": "00D36000000b28L!ARsAQMtHo4XD71VYRxoz"
}
}
},
"Body": {
"@ns": "soapenv",
"query": {
"@ns": "urn",
"queryString": {
"@ns": "urn",
"@value": "SELECT Id, Name FROM Account LIMIT 2"
}
}
}
}
}
xml = xml2dict(dict, customRoot=False)
print(xml)
```
output:
```
<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:urn="urn:partner.soap.sforce.com">
<soapenv:Header>
<urn:SessionHeader>
<urn:sessionId>{0}</urn:sessionId>
</urn:SessionHeader>
</soapenv:Header>
</soapenv:Envelope>
```
"""
xml_string = tostring(parse(input_dict, pretty=pretty), encoding=encoding)
if pretty:
xml_pretty_string = minidom.parseString(xml_string)
return xml_pretty_string.toprettyxml().decode(encoding)
else:
return xml_string.decode(encoding)
def parse(input_dict, parent=None, pretty=False):
parent = parent or {}
for key, value in input_dict.items():
if isinstance(value, (float, int)):
# Enfoce strings here
value = str(value)
parent["name"] = key
parent["value"] = value
if isinstance(value, dict):
if "@ns" in value:
parent["namespace"] = value.pop("@ns", None)
if "@attrs" in value:
parent["attributes"] = value.pop("@attrs", None)
if "@name" in value:
parent["name"] = value.pop("@name", None)
if "@value" in value:
val = value["@value"]
if isinstance(val, (float, int)):
# Enfoce strings here
val = str(val)
parent["value"] = value = val
if "namespace" in parent:
parent["name"] = "{}:{}".format(parent["namespace"], parent["name"])
if "attributes" in parent:
element = Element(parent["name"], parent["attributes"])
else:
element = Element(parent["name"])
if isinstance(parent["value"], dict):
for child_key, child_value in parent["value"].items():
element.append(parse({child_key: child_value}, parent={}))
elif isinstance(parent["value"], (list, set, tuple)):
for child in parent["value"]:
element.append(parse(child, parent={}))
else:
element.text = parent["value"]
return element