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