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