1 |
55
|
aaronmk
|
# XPath parsing
|
2 |
21
|
aaronmk
|
|
3 |
55
|
aaronmk
|
import copy
|
4 |
21
|
aaronmk
|
|
5 |
|
|
from Parser import Parser
|
6 |
77
|
aaronmk
|
import xml_dom
|
7 |
21
|
aaronmk
|
|
8 |
|
|
class XpathElem:
|
9 |
94
|
aaronmk
|
def __init__(self, name, value=None, is_attr=False):
|
10 |
156
|
aaronmk
|
if name == '': name = '.'
|
11 |
21
|
aaronmk
|
self.name = name
|
12 |
|
|
self.value = value
|
13 |
|
|
self.is_attr = is_attr
|
14 |
97
|
aaronmk
|
self.is_positive = True
|
15 |
94
|
aaronmk
|
self.is_ptr = False
|
16 |
|
|
self.keys = []
|
17 |
|
|
self.attrs = []
|
18 |
78
|
aaronmk
|
self.other_branches = [] # temp implementation for split paths
|
19 |
21
|
aaronmk
|
|
20 |
|
|
def __repr__(self):
|
21 |
|
|
str_ = ''
|
22 |
141
|
aaronmk
|
if not self.is_positive: str_ += '!'
|
23 |
21
|
aaronmk
|
if self.is_attr: str_ += '@'
|
24 |
25
|
aaronmk
|
str_ += self.name
|
25 |
94
|
aaronmk
|
if self.keys != []: str_ += repr(self.keys)
|
26 |
|
|
if self.attrs != []: str_ += ':'+repr(self.attrs)
|
27 |
|
|
if self.is_ptr: str_ += '->'
|
28 |
|
|
if self.other_branches != []: str_ += '{'+repr(self.other_branches)+'}'
|
29 |
25
|
aaronmk
|
if self.value != None: str_ += '='+repr(self.value)
|
30 |
21
|
aaronmk
|
return str_
|
31 |
|
|
|
32 |
|
|
def __eq__(self, other): return self.__dict__ == other.__dict__
|
33 |
|
|
|
34 |
99
|
aaronmk
|
def is_positive(path): return path[0].is_positive
|
35 |
|
|
|
36 |
24
|
aaronmk
|
def value(path): return path[-1].value
|
37 |
|
|
|
38 |
22
|
aaronmk
|
def set_value(path, value): path[-1].value = value
|
39 |
|
|
|
40 |
32
|
aaronmk
|
def backward_id(elem):
|
41 |
171
|
aaronmk
|
if len(elem.keys) >= 1 and value(elem.keys[0]) == None: return elem.keys[0]
|
42 |
32
|
aaronmk
|
else: return None
|
43 |
|
|
|
44 |
170
|
aaronmk
|
def expand_abbr(name, repl):
|
45 |
|
|
before, abbr, after = name.partition('*')
|
46 |
|
|
if abbr != '': name = before+repl+after
|
47 |
|
|
return name
|
48 |
|
|
|
49 |
154
|
aaronmk
|
_cache = {}
|
50 |
|
|
|
51 |
76
|
aaronmk
|
def parse(str_):
|
52 |
154
|
aaronmk
|
try: return _cache[str_]
|
53 |
|
|
except KeyError: pass
|
54 |
|
|
|
55 |
76
|
aaronmk
|
parser = Parser(str_)
|
56 |
21
|
aaronmk
|
|
57 |
76
|
aaronmk
|
def _path():
|
58 |
97
|
aaronmk
|
is_positive = not parser.str_('!')
|
59 |
|
|
|
60 |
21
|
aaronmk
|
tree = []
|
61 |
|
|
while True:
|
62 |
38
|
aaronmk
|
# Split path
|
63 |
76
|
aaronmk
|
if parser.str_('{'):
|
64 |
94
|
aaronmk
|
tree[-1].other_branches = _paths()
|
65 |
76
|
aaronmk
|
parser.str_('}', required=True)
|
66 |
94
|
aaronmk
|
tree += tree[-1].other_branches.pop(0) # use first path for now
|
67 |
38
|
aaronmk
|
break # nothing allowed after split path
|
68 |
36
|
aaronmk
|
|
69 |
76
|
aaronmk
|
elem = XpathElem(is_attr=parser.str_('@'),
|
70 |
156
|
aaronmk
|
name=parser.re(r'[\w.*]*', required=True))
|
71 |
38
|
aaronmk
|
|
72 |
94
|
aaronmk
|
# Keys used to match nodes
|
73 |
76
|
aaronmk
|
if parser.str_('['):
|
74 |
94
|
aaronmk
|
elem.keys = _paths()
|
75 |
76
|
aaronmk
|
parser.str_(']', required=True)
|
76 |
36
|
aaronmk
|
|
77 |
94
|
aaronmk
|
# Attrs created when no matching node exists
|
78 |
|
|
if parser.str_(':'):
|
79 |
|
|
parser.str_('[', required=True)
|
80 |
|
|
elem.attrs = _paths()
|
81 |
|
|
parser.str_(']', required=True)
|
82 |
|
|
|
83 |
76
|
aaronmk
|
elem.is_ptr = parser.str_('->')
|
84 |
21
|
aaronmk
|
tree.append(elem)
|
85 |
36
|
aaronmk
|
|
86 |
|
|
# Lookahead assertion
|
87 |
76
|
aaronmk
|
if parser.str_('('):
|
88 |
|
|
parser.str_('/', required=True) # next / is inside ()
|
89 |
|
|
path = _path()
|
90 |
|
|
parser.str_(')', required=True)
|
91 |
94
|
aaronmk
|
elem.keys.append(path)
|
92 |
36
|
aaronmk
|
tree += path
|
93 |
|
|
|
94 |
76
|
aaronmk
|
if not parser.str_('/'): break
|
95 |
32
|
aaronmk
|
|
96 |
97
|
aaronmk
|
tree[0].is_positive = is_positive
|
97 |
|
|
|
98 |
|
|
# Value
|
99 |
91
|
aaronmk
|
if parser.str_('='):
|
100 |
|
|
if parser.str_('"'):
|
101 |
|
|
value = parser.re(r'[^"]*')
|
102 |
|
|
parser.str_('"', required=True)
|
103 |
92
|
aaronmk
|
else: value = parser.re(r'[\w.]*')
|
104 |
91
|
aaronmk
|
set_value(tree, value)
|
105 |
85
|
aaronmk
|
|
106 |
32
|
aaronmk
|
# Expand * abbrs
|
107 |
70
|
aaronmk
|
for i in reversed(xrange(len(tree))):
|
108 |
|
|
elem = tree[i]
|
109 |
171
|
aaronmk
|
if elem.is_ptr: offset = 2
|
110 |
32
|
aaronmk
|
else: offset = 1
|
111 |
170
|
aaronmk
|
try: repl = tree[i+offset].name
|
112 |
171
|
aaronmk
|
except IndexError: pass # no replacement elem
|
113 |
|
|
else: elem.name = expand_abbr(elem.name, repl)
|
114 |
32
|
aaronmk
|
|
115 |
21
|
aaronmk
|
return tree
|
116 |
76
|
aaronmk
|
|
117 |
94
|
aaronmk
|
def _paths():
|
118 |
|
|
paths = []
|
119 |
|
|
while True:
|
120 |
|
|
paths.append(_path())
|
121 |
|
|
if not parser.str_(','): break
|
122 |
|
|
return paths
|
123 |
|
|
|
124 |
76
|
aaronmk
|
parser.str_('/') # optional leading /
|
125 |
|
|
path = _path()
|
126 |
|
|
parser.end()
|
127 |
154
|
aaronmk
|
_cache[str_] = path
|
128 |
76
|
aaronmk
|
return path
|
129 |
21
|
aaronmk
|
|
130 |
26
|
aaronmk
|
instance_level = 1
|
131 |
22
|
aaronmk
|
|
132 |
26
|
aaronmk
|
def obj(path):
|
133 |
55
|
aaronmk
|
obj_path = copy.deepcopy(path[:instance_level+1])
|
134 |
26
|
aaronmk
|
obj_path[-1].is_ptr = False # prevent pointer w/o target
|
135 |
|
|
return obj_path
|
136 |
|
|
|
137 |
22
|
aaronmk
|
def set_id(path, id_, has_types=True):
|
138 |
26
|
aaronmk
|
if has_types: id_level = instance_level
|
139 |
21
|
aaronmk
|
else: id_level = 0
|
140 |
94
|
aaronmk
|
path[id_level].keys.append([XpathElem('id', id_, True)])
|
141 |
62
|
aaronmk
|
|
142 |
|
|
def is_id(path): return path[0].is_attr and path[0].name == 'id'
|
143 |
|
|
|
144 |
94
|
aaronmk
|
def is_instance(elem): return elem.keys != [] and is_id(elem.keys[0])
|
145 |
77
|
aaronmk
|
|
146 |
141
|
aaronmk
|
def get(parent, xpath, create=False, last_only=None):
|
147 |
|
|
'''Warning: The last_only optimization may put data that should be together
|
148 |
|
|
into separate nodes'''
|
149 |
77
|
aaronmk
|
if last_only == None: last_only = create
|
150 |
154
|
aaronmk
|
if type(xpath) == str: xpath = parse(xpath)
|
151 |
99
|
aaronmk
|
|
152 |
165
|
aaronmk
|
if xpath == []: return parent
|
153 |
99
|
aaronmk
|
if create and not is_positive(xpath): return None
|
154 |
135
|
aaronmk
|
doc = parent.ownerDocument
|
155 |
141
|
aaronmk
|
root = doc.documentElement
|
156 |
165
|
aaronmk
|
elem = xpath[0]
|
157 |
|
|
|
158 |
|
|
# Find possible matches
|
159 |
|
|
children = []
|
160 |
|
|
if elem.is_attr:
|
161 |
|
|
child = parent.getAttributeNode(elem.name)
|
162 |
|
|
if child != None: children = [child]
|
163 |
|
|
elif elem.name == '.': children = [parent]
|
164 |
|
|
else:
|
165 |
|
|
children = xml_dom.by_tag_name(parent, elem.name,
|
166 |
|
|
last_only and (elem.keys == [] or is_instance(elem)))
|
167 |
|
|
|
168 |
|
|
# Check each match
|
169 |
|
|
node = None
|
170 |
|
|
for child in children:
|
171 |
|
|
is_match = elem.value == None or xml_dom.value(child) == elem.value
|
172 |
|
|
for attr in elem.keys:
|
173 |
|
|
if not is_match: break
|
174 |
|
|
is_match = (get(child, attr, False, last_only) != None)\
|
175 |
|
|
== is_positive(attr)
|
176 |
|
|
if is_match: node = child; break
|
177 |
|
|
|
178 |
|
|
# Create node
|
179 |
|
|
if node == None:
|
180 |
|
|
if not create: return None
|
181 |
77
|
aaronmk
|
if elem.is_attr:
|
182 |
165
|
aaronmk
|
parent.setAttribute(elem.name, '')
|
183 |
|
|
node = parent.getAttributeNode(elem.name)
|
184 |
|
|
else: node = parent.appendChild(doc.createElement(elem.name))
|
185 |
|
|
if elem.value != None: xml_dom.set_value(node, elem.value)
|
186 |
|
|
if create:
|
187 |
|
|
for attr in elem.keys + elem.attrs: get(node, attr, create, last_only)
|
188 |
|
|
|
189 |
|
|
xpath = xpath[1:] # rest of XPath
|
190 |
|
|
|
191 |
|
|
# Follow pointer
|
192 |
|
|
if elem.is_ptr:
|
193 |
|
|
xpath = copy.deepcopy(xpath)
|
194 |
171
|
aaronmk
|
id_path = backward_id(xpath[instance_level])
|
195 |
|
|
if id_path != None: # backward (child-to-parent) pointer with ID key
|
196 |
|
|
id_path[0].name = expand_abbr(id_path[0].name, node.tagName)
|
197 |
|
|
set_value(id_path, xml_dom.get_id(node)) # modify id key of xpath
|
198 |
165
|
aaronmk
|
else: # forward (parent-to-child) pointer
|
199 |
|
|
id_ = xml_dom.value(node)
|
200 |
|
|
obj_xpath = obj(xpath) # target object
|
201 |
|
|
if id_ == None or get(root, obj_xpath, False, True) == None:
|
202 |
|
|
# no target or target keys don't match
|
203 |
|
|
if not create: return None
|
204 |
|
|
|
205 |
|
|
# Use last target object's ID + 1
|
206 |
|
|
obj_xpath[-1].keys = [] # just get by tag name
|
207 |
|
|
last = get(root, obj_xpath, False, True)
|
208 |
|
|
if last != None: id_ = str(int(xml_dom.get_id(last)) + 1)
|
209 |
|
|
else: id_ = '0'
|
210 |
|
|
|
211 |
|
|
# Will append if target keys didn't match.
|
212 |
|
|
# Use lookahead assertion to avoid this.
|
213 |
|
|
xml_dom.set_value(node, id_)
|
214 |
|
|
else: last_only = False
|
215 |
|
|
set_id(xpath, id_)
|
216 |
|
|
else: root = node
|
217 |
|
|
next = get(root, xpath, create, last_only)
|
218 |
|
|
|
219 |
|
|
for branch in elem.other_branches:
|
220 |
|
|
branch = copy.deepcopy(branch)
|
221 |
|
|
set_value(branch, value(xpath))
|
222 |
|
|
get(node, branch, create, last_only)
|
223 |
|
|
|
224 |
|
|
return next
|
225 |
82
|
aaronmk
|
|
226 |
141
|
aaronmk
|
def put_obj(root, xpath, id_, has_types, value=None):
|
227 |
155
|
aaronmk
|
if type(xpath) == str: xpath = parse(xpath)
|
228 |
|
|
|
229 |
82
|
aaronmk
|
xpath = copy.deepcopy(xpath) # don't modify input!
|
230 |
|
|
set_id(xpath, id_, has_types)
|
231 |
85
|
aaronmk
|
if value != None: set_value(xpath, value)
|
232 |
141
|
aaronmk
|
get(root, xpath, True)
|
233 |
133
|
aaronmk
|
|
234 |
135
|
aaronmk
|
def path2xml(xpath, first_branch=True):
|
235 |
|
|
root = xml_dom.create_doc().documentElement
|
236 |
141
|
aaronmk
|
get(root, xpath, True)
|
237 |
135
|
aaronmk
|
return root
|
238 |
133
|
aaronmk
|
|
239 |
141
|
aaronmk
|
def xml_set_id(root, id_): xml_dom.set_id(root.firstChild, id_)
|