1
|
# XPath parsing
|
2
|
|
3
|
import copy
|
4
|
import warnings
|
5
|
|
6
|
from Parser import Parser
|
7
|
import util
|
8
|
import xml_dom
|
9
|
|
10
|
##### Path elements
|
11
|
|
12
|
class XpathElem:
|
13
|
def __init__(self, name='', value=None, is_attr=False):
|
14
|
self.name = name
|
15
|
self.value = value
|
16
|
self.is_attr = is_attr
|
17
|
self.is_positive = True
|
18
|
self.is_ptr = False
|
19
|
self.keys = []
|
20
|
self.attrs = []
|
21
|
self.other_branches = [] # temp implementation for split paths
|
22
|
|
23
|
def __repr__(self):
|
24
|
str_ = ''
|
25
|
if not self.is_positive: str_ += '!'
|
26
|
if self.is_attr: str_ += '@'
|
27
|
if self.name == '': str_ += '""'
|
28
|
else: str_ += self.name
|
29
|
if self.keys != []: str_ += repr(self.keys)
|
30
|
if self.attrs != []: str_ += ':'+repr(self.attrs)
|
31
|
if self.is_ptr: str_ += '->'
|
32
|
if self.other_branches != []: str_ += '{'+repr(self.other_branches)+'}'
|
33
|
if self.value != None: str_ += '='+repr(self.value)
|
34
|
return str_
|
35
|
|
36
|
def __eq__(self, other): return self.__dict__ == other.__dict__
|
37
|
|
38
|
empty_elem = XpathElem()
|
39
|
|
40
|
def elem_is_empty(elem): return elem == empty_elem
|
41
|
|
42
|
def is_self(elem): return elem.name == '' or elem.name == '.'
|
43
|
|
44
|
def is_parent(elem): return elem.name == '..'
|
45
|
|
46
|
##### Paths
|
47
|
|
48
|
def is_positive(path): return path[0].is_positive
|
49
|
|
50
|
def is_rooted(path): return elem_is_empty(path[0])
|
51
|
|
52
|
def value(path): return path[-1].value
|
53
|
|
54
|
def set_value(path, value): path[-1].value = value
|
55
|
|
56
|
def backward_id(elem):
|
57
|
if len(elem.keys) >= 1 and value(elem.keys[0]) == None: return elem.keys[0]
|
58
|
else: return None
|
59
|
|
60
|
instance_level = 1 # root's grandchildren
|
61
|
|
62
|
def obj(path):
|
63
|
obj_path = copy.deepcopy(path[:instance_level+1])
|
64
|
obj_path[-1].is_ptr = False # prevent pointer w/o target
|
65
|
return obj_path
|
66
|
|
67
|
def set_id(path, id_, has_types=True):
|
68
|
if has_types: id_level = instance_level
|
69
|
else: id_level = 0 # root's children
|
70
|
if is_self(path[0]): id_level += 1 # explicit root element
|
71
|
path[id_level].keys.append([XpathElem('id', id_, True)])
|
72
|
|
73
|
def is_id(path): return path[0].is_attr and path[0].name == 'id'
|
74
|
|
75
|
def is_instance(elem): return elem.keys != [] and is_id(elem.keys[0])
|
76
|
|
77
|
##### Parsing
|
78
|
|
79
|
def expand_abbr(name, repl):
|
80
|
before, abbr, after = name.partition('*')
|
81
|
if abbr != '': name = before+repl+after
|
82
|
return name
|
83
|
|
84
|
_cache = {}
|
85
|
|
86
|
def parse(str_):
|
87
|
try: return _cache[str_]
|
88
|
except KeyError: pass
|
89
|
|
90
|
parser = Parser(str_)
|
91
|
|
92
|
def _path():
|
93
|
is_positive = not parser.str_('!')
|
94
|
|
95
|
tree = []
|
96
|
while True:
|
97
|
# Split path
|
98
|
if parser.str_('{'):
|
99
|
last = tree[-1]
|
100
|
last.other_branches = _paths()
|
101
|
parser.str_('}', required=True)
|
102
|
if parser.str_('/'): # common subpath after {}
|
103
|
subpath = _path()
|
104
|
for branch in last.other_branches: branch += subpath
|
105
|
tree += last.other_branches.pop(0) # use first path for now
|
106
|
break # anything after split path has already been parsed
|
107
|
|
108
|
elem = XpathElem(is_attr=parser.str_('@'), name=_value())
|
109
|
|
110
|
# Keys used to match nodes
|
111
|
if parser.str_('['):
|
112
|
elem.keys = _paths()
|
113
|
parser.str_(']', required=True)
|
114
|
|
115
|
# Attrs created when no matching node exists
|
116
|
if parser.str_(':'):
|
117
|
parser.str_('[', required=True)
|
118
|
elem.attrs = _paths()
|
119
|
parser.str_(']', required=True)
|
120
|
|
121
|
elem.is_ptr = parser.str_('->')
|
122
|
tree.append(elem)
|
123
|
|
124
|
# Lookahead assertion
|
125
|
if parser.str_('('):
|
126
|
parser.str_('/', required=True) # next / is inside ()
|
127
|
path = _path()
|
128
|
parser.str_(')', required=True)
|
129
|
elem.keys.append(path)
|
130
|
tree += path
|
131
|
|
132
|
if not parser.str_('/'): break
|
133
|
|
134
|
tree[0].is_positive = is_positive
|
135
|
|
136
|
# Value
|
137
|
if parser.str_('='):
|
138
|
if parser.str_('$'): # reference (different from a pointer)
|
139
|
value = _path()
|
140
|
else: value = _value() # literal value
|
141
|
set_value(tree, value)
|
142
|
|
143
|
# Expand * abbrs
|
144
|
for i in reversed(xrange(len(tree))):
|
145
|
elem = tree[i]
|
146
|
if elem.is_ptr: offset = 2
|
147
|
else: offset = 1
|
148
|
try: repl = tree[i+offset].name
|
149
|
except IndexError: pass # no replacement elem
|
150
|
else: elem.name = expand_abbr(elem.name, repl)
|
151
|
|
152
|
return tree
|
153
|
|
154
|
def _value():
|
155
|
if parser.str_('"'):
|
156
|
value = parser.re(r'[^"]*')
|
157
|
parser.str_('"', required=True)
|
158
|
else: value = parser.re(r'(?:(?:\w+:)*[\w.*]+)?')
|
159
|
return value
|
160
|
|
161
|
def _paths():
|
162
|
paths = []
|
163
|
while True:
|
164
|
paths.append(_path())
|
165
|
if not parser.str_(','): break
|
166
|
return paths
|
167
|
|
168
|
path = _path()
|
169
|
parser.end()
|
170
|
_cache[str_] = path
|
171
|
return path
|
172
|
|
173
|
##### Querying/creating XML trees
|
174
|
|
175
|
def get(root, xpath, create=False, last_only=None, limit=1, allow_rooted=True):
|
176
|
'''Warning: The last_only optimization may put data that should be together
|
177
|
into separate nodes'''
|
178
|
if last_only == None: last_only = create
|
179
|
if limit == None or limit > 1: last_only = False
|
180
|
if util.is_str(xpath): xpath = parse(xpath)
|
181
|
|
182
|
# Handle edge cases
|
183
|
if xpath == []: return [root]
|
184
|
if create and not is_positive(xpath): return []
|
185
|
|
186
|
# Define vars
|
187
|
doc = root.ownerDocument
|
188
|
if allow_rooted and is_rooted(xpath): root = doc.documentElement
|
189
|
elem = xpath[0]
|
190
|
|
191
|
# Find possible matches
|
192
|
children = []
|
193
|
if elem.is_attr:
|
194
|
child = root.getAttributeNode(elem.name)
|
195
|
if child != None: children = [child]
|
196
|
elif is_self(elem): children = [root]
|
197
|
elif is_parent(elem):
|
198
|
parent = xml_dom.parent(root)
|
199
|
if parent == None: return [] # don't try to create doc root's parent
|
200
|
root = parent
|
201
|
children = [root]
|
202
|
else:
|
203
|
children = xml_dom.by_tag_name(root, elem.name,
|
204
|
last_only and (elem.keys == [] or is_instance(elem)))
|
205
|
|
206
|
# Retrieve elem value
|
207
|
value_ = elem.value
|
208
|
if util.is_list(value_): # reference (different from a pointer)
|
209
|
targets = get(root, value_)
|
210
|
try: target = targets[0]
|
211
|
except IndexError:
|
212
|
warnings.warn(UserWarning('XPath reference target missing: '
|
213
|
+str(value_)+'\nXPath: '+str(xpath)))
|
214
|
value_ = None
|
215
|
else: value_ = xml_dom.value(target)
|
216
|
|
217
|
# Check each match
|
218
|
nodes = []
|
219
|
for child in children:
|
220
|
is_match = value_ == None or xml_dom.value(child) == value_
|
221
|
for attr in elem.keys:
|
222
|
if not is_match: break
|
223
|
is_match = ((get(child, attr, False, last_only,
|
224
|
allow_rooted=False) != []) == is_positive(attr))
|
225
|
if is_match:
|
226
|
nodes.append(child)
|
227
|
if limit != None and len(nodes) >= limit: break
|
228
|
|
229
|
# Create node
|
230
|
if nodes == []:
|
231
|
if not create: return []
|
232
|
if elem.is_attr:
|
233
|
root.setAttribute(elem.name, '')
|
234
|
node = root.getAttributeNode(elem.name)
|
235
|
elif util.list_eq_is(children, [root]): node = root
|
236
|
else: node = root.appendChild(doc.createElement(elem.name))
|
237
|
if value_ != None: xml_dom.set_value(node, value_)
|
238
|
nodes.append(node)
|
239
|
|
240
|
path_value = value(xpath)
|
241
|
xpath = xpath[1:] # rest of XPath
|
242
|
|
243
|
next = []
|
244
|
for node in nodes:
|
245
|
# Create attrs
|
246
|
if create:
|
247
|
for attr in elem.keys + elem.attrs:
|
248
|
get(node, attr, create, last_only, allow_rooted=False)
|
249
|
|
250
|
# Follow pointer
|
251
|
if elem.is_ptr:
|
252
|
root = doc.documentElement
|
253
|
xpath = copy.deepcopy(xpath)
|
254
|
id_path = backward_id(xpath[instance_level])
|
255
|
if id_path != None: # backward (child-to-parent) pointer with ID key
|
256
|
id_path[0].name = expand_abbr(id_path[0].name, node.tagName)
|
257
|
set_value(id_path, xml_dom.get_id(node)) # modify xpath's id key
|
258
|
else: # forward (parent-to-child) pointer
|
259
|
id_ = xml_dom.value(node)
|
260
|
obj_xpath = obj(xpath) # target object
|
261
|
if id_ == None or get(root, obj_xpath, False, True) == []:
|
262
|
# no target or target keys don't match
|
263
|
if not create: continue
|
264
|
|
265
|
# Use last target object's ID + 1
|
266
|
obj_xpath[-1].keys = [] # just get by tag name
|
267
|
last = get(root, obj_xpath, False, True)
|
268
|
if last != []: id_ = str(int(xml_dom.get_id(last[0])) + 1)
|
269
|
else: id_ = '0'
|
270
|
|
271
|
# Will append if target keys didn't match.
|
272
|
# Use lookahead assertion to avoid this.
|
273
|
xml_dom.set_value(node, id_)
|
274
|
else: last_only = False
|
275
|
set_id(xpath, id_)
|
276
|
else: root = node
|
277
|
next += get(root, xpath, create, last_only, limit, allow_rooted=False)
|
278
|
|
279
|
for branch in elem.other_branches:
|
280
|
branch = copy.deepcopy(branch)
|
281
|
set_value(branch, path_value)
|
282
|
next += get(node, branch, create, last_only, limit,
|
283
|
allow_rooted=False)
|
284
|
|
285
|
return next
|
286
|
|
287
|
def put_obj(root, xpath, id_, has_types, value=None):
|
288
|
if util.is_str(xpath): xpath = parse(xpath)
|
289
|
|
290
|
xpath = copy.deepcopy(xpath) # don't modify input!
|
291
|
set_id(xpath, id_, has_types)
|
292
|
if value != None: set_value(xpath, value)
|
293
|
get(root, xpath, True)
|
294
|
|
295
|
def path2xml(xpath, first_branch=True):
|
296
|
root = xml_dom.create_doc().documentElement
|
297
|
get(root, xpath, True)
|
298
|
return root
|
299
|
|
300
|
def xml_set_id(root, id_): xml_dom.set_id(root.firstChild, id_)
|