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 create and not is_positive(xpath): return None
|
152
|
doc = parent.ownerDocument
|
153
|
root = doc.documentElement
|
154
|
for elem_idx, elem in enumerate(xpath):
|
155
|
# Find possible matches
|
156
|
children = []
|
157
|
if elem.is_attr:
|
158
|
child = parent.getAttributeNode(elem.name)
|
159
|
if child != None: children = [child]
|
160
|
elif elem.name == '.': children = [parent]
|
161
|
else:
|
162
|
children = xml_dom.by_tag_name(parent, elem.name,
|
163
|
last_only and (elem.keys == [] or is_instance(elem)))
|
164
|
|
165
|
# Check each match
|
166
|
node = None
|
167
|
for child in children:
|
168
|
is_match = elem.value == None or xml_dom.value(child) == elem.value
|
169
|
for attr in elem.keys:
|
170
|
if not is_match: break
|
171
|
is_match = (get(child, attr, False, last_only) != None)\
|
172
|
== is_positive(attr)
|
173
|
if is_match: node = child; break
|
174
|
|
175
|
# Create node
|
176
|
if node == None:
|
177
|
if not create: return None
|
178
|
if elem.is_attr:
|
179
|
parent.setAttribute(elem.name, '')
|
180
|
node = parent.getAttributeNode(elem.name)
|
181
|
else: node = parent.appendChild(doc.createElement(elem.name))
|
182
|
if elem.value != None: xml_dom.set_value(node, elem.value)
|
183
|
if create:
|
184
|
for attr in elem.keys + elem.attrs:
|
185
|
get(node, attr, create, last_only)
|
186
|
|
187
|
for branch in elem.other_branches:
|
188
|
branch = copy.deepcopy(branch)
|
189
|
set_value(branch, value(xpath))
|
190
|
get(node, branch, create, last_only)
|
191
|
|
192
|
# Follow pointer
|
193
|
if elem.is_ptr:
|
194
|
xpath = copy.deepcopy(xpath[elem_idx+1:]) # rest of XPath
|
195
|
id_elem = backward_id(xpath[instance_level])
|
196
|
if id_elem != None:
|
197
|
# backward (child-to-parent) pointer with target ID attr
|
198
|
set_value(id_elem, xml_dom.get_id(node))
|
199
|
else: # forward (parent-to-child) pointer
|
200
|
id_ = xml_dom.value(node)
|
201
|
obj_xpath = obj(xpath) # target object
|
202
|
if id_ == None or get(root, obj_xpath, False, True) == None:
|
203
|
# no target or target keys don't match
|
204
|
if not create: return None
|
205
|
|
206
|
# Use last target object's ID + 1
|
207
|
obj_xpath[-1].keys = [] # just get by tag name
|
208
|
last = get(root, obj_xpath, False, True)
|
209
|
if last != None: id_ = str(int(xml_dom.get_id(last)) + 1)
|
210
|
else: id_ = '0'
|
211
|
|
212
|
# Will append if target keys didn't match. Place ! in XPath
|
213
|
# after element to fork at to avoid this.
|
214
|
xml_dom.set_value(node, id_)
|
215
|
else: last_only = False
|
216
|
set_id(xpath, id_)
|
217
|
return get(root, xpath, create, last_only)
|
218
|
|
219
|
parent = node
|
220
|
return parent
|
221
|
|
222
|
def put_obj(root, xpath, id_, has_types, value=None):
|
223
|
if type(xpath) == str: xpath = parse(xpath)
|
224
|
|
225
|
xpath = copy.deepcopy(xpath) # don't modify input!
|
226
|
set_id(xpath, id_, has_types)
|
227
|
if value != None: set_value(xpath, value)
|
228
|
get(root, xpath, True)
|
229
|
|
230
|
def path2xml(xpath, first_branch=True):
|
231
|
root = xml_dom.create_doc().documentElement
|
232
|
get(root, xpath, True)
|
233
|
return root
|
234
|
|
235
|
def xml_set_id(root, id_): xml_dom.set_id(root.firstChild, id_)
|