forked from cms-sw/cmssw
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathXML2Python.py
276 lines (225 loc) · 8.87 KB
/
XML2Python.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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
## Original version of code heavily based on recipe written by Wai Yip
## Tung, released under PSF license.
## http://code.activestate.com/recipes/534109/
import re
import os
import xml.sax.handler
import pprint
class DataNode (object):
spaces = 4
def __init__ (self, **kwargs):
self._attrs = {} # XML attributes and child elements
self._data = None # child text data
self._ncDict = kwargs.get ('nameChangeDict', {})
def __len__ (self):
# treat single element as a list of 1
return 1
def __getitem__ (self, key):
if isinstance (key, str):
return self._attrs.get(key,None)
else:
return [self][key]
def __contains__ (self, name):
return name in self._attrs
def __nonzero__ (self):
return bool (self._attrs or self._data)
def __getattr__ (self, name):
if name.startswith('__'):
# need to do this for Python special methods???
raise AttributeError (name)
return self._attrs.get (name, None)
def _add_xml_attr (self, name, value):
change = self._ncDict.get (name)
if change:
name = change
if name in self._attrs:
# multiple attribute of the same name are represented by a list
children = self._attrs[name]
if not isinstance(children, list):
children = [children]
self._attrs[name] = children
children.append(value)
else:
self._attrs[name] = value
def __str__ (self):
return self.stringify()
def __repr__ (self):
items = sorted (self._attrs.items())
if self._data:
items.append(('data', self._data))
return u'{%s}' % ', '.join([u'%s:%s' % (k,repr(v)) for k,v in items])
def attributes (self):
return self._attrs
@staticmethod
def isiterable (obj):
return getattr (obj, '__iter__', False)
@staticmethod
def _outputValues (obj, name, offset):
retval = ' ' * offset
if name:
retval += '%s: ' % name
offset += len (name) + DataNode.spaces
# if this is a list
if isinstance (obj, list):
first = True
for value in obj:
print("value", value, value.__class__.__name__)
if first:
tempoffset = offset
first = False
retval += '[\n ' + ' ' * offset
else:
retval += ',\n ' + ' ' * offset
tempoffset = offset
if isinstance (value, DataNode):
retval += value.stringify (offset=tempoffset)
print(" calling stringify for %s" % value)
elif DataNode.isiterable (value):
retval += DataNode._outputValues (value, '', offset)
else:
retval += "%s" % value
retval += '\n' + ' ' * (offset - 2) +']\n'
return retval
retval += pprint.pformat(obj,
indent= offset,
width=1)
return retval
def stringify (self, name = '', offset = 0):
# is this just data and nothing below
if self._data and not len (self._attrs):
return _outputValues (self._data, name, offset)
retval = ' ' * offset
if name:
retval += '%s : %s\n' % \
(name,
pprint.pformat (self._data,
indent= offset+DataNode.spaces,
width=1) )
else:
retval += pprint.pformat (self._data,
indent=offset+DataNode.spaces,
width=1)
return retval
# this has attributes
retval = ''
if name:
retval += '\n' + ' ' * offset
retval += '%s: ' % name
first = True
for key, value in sorted (self._attrs.items()):
if first:
retval += '{ \n'
tempspace = offset + 3
first = False
else:
retval += ',\n'
tempspace = offset + 3
if isinstance (value, DataNode):
retval += value.stringify (key, tempspace)
else:
retval += DataNode._outputValues (value, key, tempspace)
# this has data too
if self._data:
retval += ',\n'
tempspace = offset + 3
retval += DataNode._ouptputValues (self._data, name, tempspace)
retval += '\n ' + ' ' * offset + '}'
return retval
class TreeBuilder (xml.sax.handler.ContentHandler):
non_id_char = re.compile('[^_0-9a-zA-Z]')
def __init__ (self, **kwargs):
self._stack = []
self._text_parts = []
self._ncDict = kwargs.get ('nameChangeDict', {})
self._root = DataNode (nameChangeDict = self._ncDict)
self.current = self._root
def startElement (self, name, attrs):
self._stack.append( (self.current, self._text_parts))
self.current = DataNode (nameChangeDict = self._ncDict)
self._text_parts = []
# xml attributes --> python attributes
for k, v in attrs.items():
self.current._add_xml_attr (TreeBuilder._name_mangle(k), v)
def endElement (self, name):
text = ''.join (self._text_parts).strip()
if text:
self.current._data = text
if self.current.attributes():
obj = self.current
else:
# a text only node is simply represented by the string
obj = text or ''
self.current, self._text_parts = self._stack.pop()
self.current._add_xml_attr (TreeBuilder._name_mangle(name), obj)
def characters (self, content):
self._text_parts.append(content)
def root (self):
return self._root
def topLevel (self):
'''Returns top level object'''
return list(self._root.attributes().values())[0]
@staticmethod
def _name_mangle (name):
return TreeBuilder.non_id_char.sub('_', name)
regexList = [ (re.compile (r'&'), '&' ),
(re.compile (r'<'), '<' ),
(re.compile (r'>'), '>' ),
(re.compile (r'"'), '"e;' ),
(re.compile (r"'"), ''' )
]
quoteRE = re.compile (r'(\w\s*=\s*")([^"]+)"')
def fixQuoteValue (match):
'''Changes all characters inside of the match'''
quote = match.group(2)
for regexTup in regexList:
quote = regexTup[0].sub( regexTup[1], quote )
return match.group(1) + quote + '"'
def xml2obj (**kwargs):
''' Converts XML data into native Python object. Takes either
file handle or string as input. Does NOT fix illegal characters.
input source: Exactly one of the three following is needed
filehandle - input from file handle
contents - input from string
filename - input from filename
options:
filtering - boolean value telling code whether or not to fileter
input selection to remove illegal XML characters
nameChangeDict - dictionaries of names to change in python object'''
# make sure we have exactly 1 input source
filehandle = kwargs.get ('filehandle')
contents = kwargs.get ('contents')
filename = kwargs.get ('filename')
if not filehandle and not contents and not filename:
raise RuntimeError("You must provide 'filehandle', 'contents', or 'filename'")
if filehandle and contents or \
filehandle and filename or \
contents and filename:
raise RuntimeError("You must provide only ONE of 'filehandle', 'contents', or 'filename'")
# are we filtering?
filtering = kwargs.get ('filtering')
if filtering:
# if we are filtering, we need to read in the contents to modify them
if not contents:
if not filehandle:
try:
filehandle = open (filename, 'r')
except:
raise RuntimeError("Failed to open '%s'" % filename)
contents = ''
for line in filehandle:
contents += line
filehandle.close()
filehandle = filename = ''
contents = quoteRE.sub (fixQuoteValue, contents)
ncDict = kwargs.get ('nameChangeDict', {})
builder = TreeBuilder (nameChangeDict = ncDict)
if contents:
xml.sax.parseString(contents, builder)
else:
if not filehandle:
try:
filehandle = open (filename, 'r')
except:
raise RuntimeError("Failed to open '%s'" % filename)
xml.sax.parse(filehandle, builder)
return builder.topLevel()