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