1 |
55
|
aaronmk
|
# XPath parsing
|
2 |
21
|
aaronmk
|
|
3 |
55
|
aaronmk
|
import copy
|
4 |
1009
|
aaronmk
|
import warnings
|
5 |
21
|
aaronmk
|
|
6 |
|
|
from Parser import Parser
|
7 |
892
|
aaronmk
|
import util
|
8 |
77
|
aaronmk
|
import xml_dom
|
9 |
21
|
aaronmk
|
|
10 |
1001
|
aaronmk
|
##### Path elements
|
11 |
|
|
|
12 |
21
|
aaronmk
|
class XpathElem:
|
13 |
1002
|
aaronmk
|
def __init__(self, name='', value=None, is_attr=False):
|
14 |
21
|
aaronmk
|
self.name = name
|
15 |
|
|
self.value = value
|
16 |
|
|
self.is_attr = is_attr
|
17 |
97
|
aaronmk
|
self.is_positive = True
|
18 |
1238
|
aaronmk
|
self.is_lookup_only = False
|
19 |
94
|
aaronmk
|
self.is_ptr = False
|
20 |
|
|
self.keys = []
|
21 |
|
|
self.attrs = []
|
22 |
78
|
aaronmk
|
self.other_branches = [] # temp implementation for split paths
|
23 |
21
|
aaronmk
|
|
24 |
|
|
def __repr__(self):
|
25 |
|
|
str_ = ''
|
26 |
141
|
aaronmk
|
if not self.is_positive: str_ += '!'
|
27 |
21
|
aaronmk
|
if self.is_attr: str_ += '@'
|
28 |
1004
|
aaronmk
|
if self.name == '': str_ += '""'
|
29 |
|
|
else: str_ += self.name
|
30 |
1238
|
aaronmk
|
if self.is_lookup_only: str_ += '?'
|
31 |
94
|
aaronmk
|
if self.keys != []: str_ += repr(self.keys)
|
32 |
|
|
if self.attrs != []: str_ += ':'+repr(self.attrs)
|
33 |
|
|
if self.is_ptr: str_ += '->'
|
34 |
|
|
if self.other_branches != []: str_ += '{'+repr(self.other_branches)+'}'
|
35 |
25
|
aaronmk
|
if self.value != None: str_ += '='+repr(self.value)
|
36 |
21
|
aaronmk
|
return str_
|
37 |
|
|
|
38 |
|
|
def __eq__(self, other): return self.__dict__ == other.__dict__
|
39 |
|
|
|
40 |
1002
|
aaronmk
|
empty_elem = XpathElem()
|
41 |
|
|
|
42 |
|
|
def elem_is_empty(elem): return elem == empty_elem
|
43 |
|
|
|
44 |
1004
|
aaronmk
|
def is_self(elem): return elem.name == '' or elem.name == '.'
|
45 |
|
|
|
46 |
|
|
def is_parent(elem): return elem.name == '..'
|
47 |
|
|
|
48 |
3328
|
aaronmk
|
def is_all(elem): return elem.name == '*'
|
49 |
|
|
|
50 |
1001
|
aaronmk
|
##### Paths
|
51 |
|
|
|
52 |
2010
|
aaronmk
|
def is_xpath(value):
|
53 |
|
|
return isinstance(value, list) and (len(value) == 0
|
54 |
|
|
or isinstance(value[0], XpathElem))
|
55 |
|
|
|
56 |
1350
|
aaronmk
|
def path_is_empty(path): return path == [] or path == [empty_elem]
|
57 |
|
|
|
58 |
99
|
aaronmk
|
def is_positive(path): return path[0].is_positive
|
59 |
|
|
|
60 |
1003
|
aaronmk
|
def is_rooted(path): return elem_is_empty(path[0])
|
61 |
|
|
|
62 |
24
|
aaronmk
|
def value(path): return path[-1].value
|
63 |
|
|
|
64 |
1294
|
aaronmk
|
def set_value(path, value):
|
65 |
|
|
'''Caller must make a shallow copy of the path to prevent modifications from
|
66 |
|
|
propagating to other copies of the path (a deep copy is not needed)'''
|
67 |
|
|
path[-1] = copy.copy(path[-1]) # don't modify other copies of the path
|
68 |
|
|
path[-1].value = value
|
69 |
22
|
aaronmk
|
|
70 |
1577
|
aaronmk
|
def append(path, subpath, i=0):
|
71 |
|
|
'''Recursively appends subpath to every leaf of a path tree'''
|
72 |
|
|
if i >= len(path): path += subpath
|
73 |
|
|
else:
|
74 |
|
|
append(path, subpath, i+1)
|
75 |
|
|
for branch in path[i].other_branches: append(branch, subpath)
|
76 |
|
|
|
77 |
32
|
aaronmk
|
def backward_id(elem):
|
78 |
171
|
aaronmk
|
if len(elem.keys) >= 1 and value(elem.keys[0]) == None: return elem.keys[0]
|
79 |
32
|
aaronmk
|
else: return None
|
80 |
|
|
|
81 |
1001
|
aaronmk
|
instance_level = 1 # root's grandchildren
|
82 |
|
|
|
83 |
|
|
def obj(path):
|
84 |
|
|
obj_path = copy.deepcopy(path[:instance_level+1])
|
85 |
|
|
obj_path[-1].is_ptr = False # prevent pointer w/o target
|
86 |
|
|
return obj_path
|
87 |
|
|
|
88 |
|
|
def set_id(path, id_, has_types=True):
|
89 |
1294
|
aaronmk
|
'''Caller must make a shallow copy of the path to prevent modifications from
|
90 |
2001
|
aaronmk
|
propagating to other copies of the path (a deep copy is not needed).
|
91 |
|
|
@return The path to the ID attr, which can be used to change the ID
|
92 |
|
|
'''
|
93 |
1001
|
aaronmk
|
if has_types: id_level = instance_level
|
94 |
|
|
else: id_level = 0 # root's children
|
95 |
1004
|
aaronmk
|
if is_self(path[0]): id_level += 1 # explicit root element
|
96 |
1294
|
aaronmk
|
|
97 |
|
|
id_elem = path[id_level] = copy.copy(path[id_level])
|
98 |
|
|
# don't modify other copies of the path
|
99 |
|
|
id_elem.keys = id_elem.keys[:] # don't modify other copies of the elem
|
100 |
2001
|
aaronmk
|
id_attr = XpathElem('id', None, is_attr=True)
|
101 |
|
|
|
102 |
|
|
# Save the path to the ID attr
|
103 |
2003
|
aaronmk
|
id_path = obj(path) # a copy of the path up through the ID level
|
104 |
2002
|
aaronmk
|
id_path.append(copy.copy(id_attr)) # this path's id_attr is independent
|
105 |
2001
|
aaronmk
|
|
106 |
|
|
# Set the ID attr on the provided XPath
|
107 |
|
|
id_attr.value = id_
|
108 |
|
|
id_elem.keys.append([id_attr])
|
109 |
|
|
|
110 |
|
|
return id_path
|
111 |
1001
|
aaronmk
|
|
112 |
|
|
def is_id(path): return path[0].is_attr and path[0].name == 'id'
|
113 |
|
|
|
114 |
1070
|
aaronmk
|
def is_instance(elem): return elem.keys != [] and is_id(elem.keys[0])
|
115 |
1001
|
aaronmk
|
|
116 |
|
|
##### Parsing
|
117 |
|
|
|
118 |
1345
|
aaronmk
|
import xpath_func
|
119 |
|
|
|
120 |
170
|
aaronmk
|
def expand_abbr(name, repl):
|
121 |
|
|
before, abbr, after = name.partition('*')
|
122 |
|
|
if abbr != '': name = before+repl+after
|
123 |
|
|
return name
|
124 |
|
|
|
125 |
154
|
aaronmk
|
_cache = {}
|
126 |
|
|
|
127 |
76
|
aaronmk
|
def parse(str_):
|
128 |
154
|
aaronmk
|
try: return _cache[str_]
|
129 |
|
|
except KeyError: pass
|
130 |
|
|
|
131 |
76
|
aaronmk
|
parser = Parser(str_)
|
132 |
21
|
aaronmk
|
|
133 |
76
|
aaronmk
|
def _path():
|
134 |
97
|
aaronmk
|
is_positive = not parser.str_('!')
|
135 |
|
|
|
136 |
21
|
aaronmk
|
tree = []
|
137 |
|
|
while True:
|
138 |
38
|
aaronmk
|
# Split path
|
139 |
76
|
aaronmk
|
if parser.str_('{'):
|
140 |
1398
|
aaronmk
|
try: last = tree[-1]
|
141 |
|
|
except IndexError: parser.syntax_err('./{')
|
142 |
1070
|
aaronmk
|
last.other_branches = _paths()
|
143 |
1577
|
aaronmk
|
tree += last.other_branches.pop(0) # use first path for now
|
144 |
76
|
aaronmk
|
parser.str_('}', required=True)
|
145 |
1577
|
aaronmk
|
if parser.str_('/'): append(tree, _path()) # subpath after {}
|
146 |
1070
|
aaronmk
|
break # anything after split path has already been parsed
|
147 |
36
|
aaronmk
|
|
148 |
754
|
aaronmk
|
elem = XpathElem(is_attr=parser.str_('@'), name=_value())
|
149 |
38
|
aaronmk
|
|
150 |
1238
|
aaronmk
|
elem.is_lookup_only = parser.str_('?')
|
151 |
|
|
|
152 |
94
|
aaronmk
|
# Keys used to match nodes
|
153 |
76
|
aaronmk
|
if parser.str_('['):
|
154 |
94
|
aaronmk
|
elem.keys = _paths()
|
155 |
76
|
aaronmk
|
parser.str_(']', required=True)
|
156 |
36
|
aaronmk
|
|
157 |
94
|
aaronmk
|
# Attrs created when no matching node exists
|
158 |
|
|
if parser.str_(':'):
|
159 |
|
|
parser.str_('[', required=True)
|
160 |
|
|
elem.attrs = _paths()
|
161 |
|
|
parser.str_(']', required=True)
|
162 |
|
|
|
163 |
76
|
aaronmk
|
elem.is_ptr = parser.str_('->')
|
164 |
21
|
aaronmk
|
tree.append(elem)
|
165 |
36
|
aaronmk
|
|
166 |
|
|
# Lookahead assertion
|
167 |
76
|
aaronmk
|
if parser.str_('('):
|
168 |
|
|
parser.str_('/', required=True) # next / is inside ()
|
169 |
|
|
path = _path()
|
170 |
|
|
parser.str_(')', required=True)
|
171 |
94
|
aaronmk
|
elem.keys.append(path)
|
172 |
36
|
aaronmk
|
tree += path
|
173 |
|
|
|
174 |
76
|
aaronmk
|
if not parser.str_('/'): break
|
175 |
32
|
aaronmk
|
|
176 |
97
|
aaronmk
|
tree[0].is_positive = is_positive
|
177 |
|
|
|
178 |
|
|
# Value
|
179 |
997
|
aaronmk
|
if parser.str_('='):
|
180 |
1009
|
aaronmk
|
if parser.str_('$'): # reference (different from a pointer)
|
181 |
|
|
value = _path()
|
182 |
|
|
else: value = _value() # literal value
|
183 |
997
|
aaronmk
|
set_value(tree, value)
|
184 |
85
|
aaronmk
|
|
185 |
32
|
aaronmk
|
# Expand * abbrs
|
186 |
70
|
aaronmk
|
for i in reversed(xrange(len(tree))):
|
187 |
|
|
elem = tree[i]
|
188 |
171
|
aaronmk
|
if elem.is_ptr: offset = 2
|
189 |
32
|
aaronmk
|
else: offset = 1
|
190 |
170
|
aaronmk
|
try: repl = tree[i+offset].name
|
191 |
171
|
aaronmk
|
except IndexError: pass # no replacement elem
|
192 |
|
|
else: elem.name = expand_abbr(elem.name, repl)
|
193 |
32
|
aaronmk
|
|
194 |
21
|
aaronmk
|
return tree
|
195 |
76
|
aaronmk
|
|
196 |
754
|
aaronmk
|
def _value():
|
197 |
|
|
if parser.str_('"'):
|
198 |
|
|
value = parser.re(r'[^"]*')
|
199 |
|
|
parser.str_('"', required=True)
|
200 |
|
|
else: value = parser.re(r'(?:(?:\w+:)*[\w.*]+)?')
|
201 |
|
|
return value
|
202 |
|
|
|
203 |
94
|
aaronmk
|
def _paths():
|
204 |
|
|
paths = []
|
205 |
1350
|
aaronmk
|
path = _path()
|
206 |
|
|
if not path_is_empty(path): # not empty list
|
207 |
|
|
paths.append(path)
|
208 |
|
|
while parser.str_(','): paths.append(_path())
|
209 |
1352
|
aaronmk
|
if path_is_empty(paths[-1]): paths.pop() # remove trailing ","
|
210 |
94
|
aaronmk
|
return paths
|
211 |
|
|
|
212 |
76
|
aaronmk
|
path = _path()
|
213 |
|
|
parser.end()
|
214 |
1342
|
aaronmk
|
path = xpath_func.process(path)
|
215 |
154
|
aaronmk
|
_cache[str_] = path
|
216 |
76
|
aaronmk
|
return path
|
217 |
21
|
aaronmk
|
|
218 |
1001
|
aaronmk
|
##### Querying/creating XML trees
|
219 |
22
|
aaronmk
|
|
220 |
1005
|
aaronmk
|
def get(root, xpath, create=False, last_only=None, limit=1, allow_rooted=True):
|
221 |
141
|
aaronmk
|
'''Warning: The last_only optimization may put data that should be together
|
222 |
|
|
into separate nodes'''
|
223 |
77
|
aaronmk
|
if last_only == None: last_only = create
|
224 |
887
|
aaronmk
|
if limit == None or limit > 1: last_only = False
|
225 |
892
|
aaronmk
|
if util.is_str(xpath): xpath = parse(xpath)
|
226 |
99
|
aaronmk
|
|
227 |
1005
|
aaronmk
|
# Handle edge cases
|
228 |
998
|
aaronmk
|
if xpath == []: return [root]
|
229 |
886
|
aaronmk
|
if create and not is_positive(xpath): return []
|
230 |
1005
|
aaronmk
|
|
231 |
|
|
# Define vars
|
232 |
998
|
aaronmk
|
doc = root.ownerDocument
|
233 |
1005
|
aaronmk
|
if allow_rooted and is_rooted(xpath): root = doc.documentElement
|
234 |
165
|
aaronmk
|
elem = xpath[0]
|
235 |
|
|
|
236 |
|
|
# Find possible matches
|
237 |
|
|
children = []
|
238 |
|
|
if elem.is_attr:
|
239 |
998
|
aaronmk
|
child = root.getAttributeNode(elem.name)
|
240 |
165
|
aaronmk
|
if child != None: children = [child]
|
241 |
1004
|
aaronmk
|
elif is_self(elem): children = [root]
|
242 |
|
|
elif is_parent(elem):
|
243 |
1000
|
aaronmk
|
parent = xml_dom.parent(root)
|
244 |
1013
|
aaronmk
|
if parent == None: return [] # don't try to create doc root's parent
|
245 |
|
|
root = parent
|
246 |
|
|
children = [root]
|
247 |
3330
|
aaronmk
|
elif is_all(elem): children = list(xml_dom.NodeElemIter(root))
|
248 |
165
|
aaronmk
|
else:
|
249 |
998
|
aaronmk
|
children = xml_dom.by_tag_name(root, elem.name,
|
250 |
1815
|
aaronmk
|
last_only=(last_only and (elem.keys == [] or is_instance(elem))),
|
251 |
|
|
ignore_namespace=False) # later set ignore_namespace to True?
|
252 |
165
|
aaronmk
|
|
253 |
1009
|
aaronmk
|
# Retrieve elem value
|
254 |
|
|
value_ = elem.value
|
255 |
|
|
if util.is_list(value_): # reference (different from a pointer)
|
256 |
|
|
targets = get(root, value_)
|
257 |
|
|
try: target = targets[0]
|
258 |
|
|
except IndexError:
|
259 |
|
|
warnings.warn(UserWarning('XPath reference target missing: '
|
260 |
|
|
+str(value_)+'\nXPath: '+str(xpath)))
|
261 |
|
|
value_ = None
|
262 |
|
|
else: value_ = xml_dom.value(target)
|
263 |
|
|
|
264 |
165
|
aaronmk
|
# Check each match
|
265 |
885
|
aaronmk
|
nodes = []
|
266 |
165
|
aaronmk
|
for child in children:
|
267 |
1009
|
aaronmk
|
is_match = value_ == None or xml_dom.value(child) == value_
|
268 |
165
|
aaronmk
|
for attr in elem.keys:
|
269 |
|
|
if not is_match: break
|
270 |
1011
|
aaronmk
|
is_match = ((get(child, attr, False, last_only,
|
271 |
|
|
allow_rooted=False) != []) == is_positive(attr))
|
272 |
885
|
aaronmk
|
if is_match:
|
273 |
|
|
nodes.append(child)
|
274 |
|
|
if limit != None and len(nodes) >= limit: break
|
275 |
165
|
aaronmk
|
|
276 |
|
|
# Create node
|
277 |
886
|
aaronmk
|
if nodes == []:
|
278 |
1239
|
aaronmk
|
if not create or elem.is_lookup_only: return []
|
279 |
77
|
aaronmk
|
if elem.is_attr:
|
280 |
998
|
aaronmk
|
root.setAttribute(elem.name, '')
|
281 |
|
|
node = root.getAttributeNode(elem.name)
|
282 |
1013
|
aaronmk
|
elif util.list_eq_is(children, [root]): node = root
|
283 |
998
|
aaronmk
|
else: node = root.appendChild(doc.createElement(elem.name))
|
284 |
1009
|
aaronmk
|
if value_ != None: xml_dom.set_value(node, value_)
|
285 |
886
|
aaronmk
|
nodes.append(node)
|
286 |
165
|
aaronmk
|
|
287 |
1009
|
aaronmk
|
path_value = value(xpath)
|
288 |
165
|
aaronmk
|
xpath = xpath[1:] # rest of XPath
|
289 |
|
|
|
290 |
886
|
aaronmk
|
next = []
|
291 |
|
|
for node in nodes:
|
292 |
|
|
# Create attrs
|
293 |
|
|
if create:
|
294 |
2556
|
aaronmk
|
# Keys last so that any lookahead assertion's path will be created
|
295 |
|
|
# last as it would have without the assertion
|
296 |
|
|
for attr in elem.attrs + elem.keys:
|
297 |
2109
|
aaronmk
|
get(node, attr, create, last_only=False, allow_rooted=False)
|
298 |
886
|
aaronmk
|
|
299 |
|
|
# Follow pointer
|
300 |
|
|
if elem.is_ptr:
|
301 |
998
|
aaronmk
|
root = doc.documentElement
|
302 |
886
|
aaronmk
|
xpath = copy.deepcopy(xpath)
|
303 |
|
|
id_path = backward_id(xpath[instance_level])
|
304 |
|
|
if id_path != None: # backward (child-to-parent) pointer with ID key
|
305 |
|
|
id_path[0].name = expand_abbr(id_path[0].name, node.tagName)
|
306 |
|
|
set_value(id_path, xml_dom.get_id(node)) # modify xpath's id key
|
307 |
|
|
else: # forward (parent-to-child) pointer
|
308 |
|
|
id_ = xml_dom.value(node)
|
309 |
|
|
obj_xpath = obj(xpath) # target object
|
310 |
|
|
if id_ == None or get(root, obj_xpath, False, True) == []:
|
311 |
|
|
# no target or target keys don't match
|
312 |
|
|
if not create: continue
|
313 |
|
|
|
314 |
|
|
# Use last target object's ID + 1
|
315 |
|
|
obj_xpath[-1].keys = [] # just get by tag name
|
316 |
|
|
last = get(root, obj_xpath, False, True)
|
317 |
1840
|
aaronmk
|
if last != []: id_ = str(int(util.coalesce(
|
318 |
|
|
xml_dom.get_id(last[0]), 0)) + 1)
|
319 |
886
|
aaronmk
|
else: id_ = '0'
|
320 |
|
|
|
321 |
|
|
# Will append if target keys didn't match.
|
322 |
|
|
# Use lookahead assertion to avoid this.
|
323 |
|
|
xml_dom.set_value(node, id_)
|
324 |
|
|
else: last_only = False
|
325 |
|
|
set_id(xpath, id_)
|
326 |
|
|
else: root = node
|
327 |
1005
|
aaronmk
|
next += get(root, xpath, create, last_only, limit, allow_rooted=False)
|
328 |
886
|
aaronmk
|
|
329 |
|
|
for branch in elem.other_branches:
|
330 |
1294
|
aaronmk
|
branch = branch[:] # don't modify input!
|
331 |
1009
|
aaronmk
|
set_value(branch, path_value)
|
332 |
1005
|
aaronmk
|
next += get(node, branch, create, last_only, limit,
|
333 |
|
|
allow_rooted=False)
|
334 |
165
|
aaronmk
|
|
335 |
|
|
return next
|
336 |
82
|
aaronmk
|
|
337 |
1320
|
aaronmk
|
def get_1(*args, **kw_args):
|
338 |
|
|
'''Runs get() and returns the first result'''
|
339 |
|
|
return util.list_get(get(*args, **kw_args), 0)
|
340 |
|
|
|
341 |
1689
|
aaronmk
|
def get_value(*args, **kw_args):
|
342 |
|
|
'''Runs get_1() and returns the value of any result node'''
|
343 |
|
|
return util.do_ignore_none(xml_dom.value, get_1(*args, **kw_args))
|
344 |
|
|
|
345 |
141
|
aaronmk
|
def put_obj(root, xpath, id_, has_types, value=None):
|
346 |
2004
|
aaronmk
|
'''@return tuple(inserted_node, id_attr_node)'''
|
347 |
892
|
aaronmk
|
if util.is_str(xpath): xpath = parse(xpath)
|
348 |
155
|
aaronmk
|
|
349 |
1294
|
aaronmk
|
xpath = xpath[:] # don't modify input!
|
350 |
2004
|
aaronmk
|
id_path = set_id(xpath, id_, has_types)
|
351 |
85
|
aaronmk
|
if value != None: set_value(xpath, value)
|
352 |
2007
|
aaronmk
|
return (get(root, xpath, True), get_1(root, id_path))
|
353 |
133
|
aaronmk
|
|
354 |
135
|
aaronmk
|
def path2xml(xpath, first_branch=True):
|
355 |
|
|
root = xml_dom.create_doc().documentElement
|
356 |
141
|
aaronmk
|
get(root, xpath, True)
|
357 |
135
|
aaronmk
|
return root
|
358 |
133
|
aaronmk
|
|
359 |
141
|
aaronmk
|
def xml_set_id(root, id_): xml_dom.set_id(root.firstChild, id_)
|