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