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